import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, DatePicker, Input, Popconfirm, Select } from 'antd'
import MyTable from '@/components/MyTable'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { A4voucherItemType, A4voucherSearchType, IA4voucherParams } from './types'
import history, { downFileFu } from '@/utils/history'
import {
  A4VOUCHER_PARAM_ROWS,
  A4VOUCHER_TABLE_COLUMNS,
  DEFAULT_A4VOUCHER_PARAMS
} from './constants'
import { MessageFu } from '@/utils/message'
import { A4_APIDownload, A4_APIList } from '@/store/action/A4voucher'
import { filterEmptyStrings } from '@/utils/objects'
import { fileImgArr } from '@/store/action/layout'
import { BUSINESS_DETAIL_PATH_MAP } from '../A3flow/data'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker

function A4voucher() {
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.A4voucher.tableInfo)
  const [formData, setFormData] = useState({ ...DEFAULT_A4VOUCHER_PARAMS })
  const formDataRef = useRef({ ...DEFAULT_A4VOUCHER_PARAMS })
  const dispatch = useDispatch()
  // 获取下载权限
  const downImg = useSelector((state: RootState) => state.A0Layout.downImg)

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: keyof IA4voucherParams) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

  // 顶部筛选
  const searchDom = useCallback(
    (arr: A4voucherSearchType[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                placeholder='请输入'
                maxLength={30}
                value={formData[item.key]}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={item.data}
                placeholder='全部'
                allowClear={true}
                value={formData[item.key as 'num'] ? formData[item.key as 'num'] : null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : item.type === '日期选择' ? (
              <RangePicker
                format='YYYY-MM-DD'
                allowClear={true}
                value={formData[item.key] as undefined}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : null}
          </div>
        )
      })
    },
    [formData, txtChangeFu]
  )

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)
  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData({ ...DEFAULT_A4VOUCHER_PARAMS })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    const { date, ...rest } = formDataRef.current
    if (Array.isArray(date) && date.length) {
      // @ts-ignore
      rest.startTime = dayjs(date[0]).format('YYYY-MM-DD') + ' 00:00:00'
      // @ts-ignore
      rest.endTime = dayjs(date[1]).format('YYYY-MM-DD') + ' 23:59:59'
    }
    dispatch(A4_APIList(filterEmptyStrings(rest)))
  }, [dispatch])

  // 点击操作按钮
  const tableBtnFu = useCallback((item: A4voucherItemType, key: string) => {
    switch (key) {
      case '1':
        history.push(`/${BUSINESS_DETAIL_PATH_MAP[item.moduleName]}/4/${item.moduleId}`)
        break
    }
  }, [])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]

          return (
            <>
              <Button size='small' type='text' onClick={() => tableBtnFu(item, '1')}>
                查看
              </Button>
              {downImg['图片'] === '原图和缩略图' &&
              fileImgArr.includes(fileNameLast.toLowerCase()) ? (
                <Popconfirm
                  title='请选择图片规格'
                  onConfirm={() => downFileFu(item.filePath)}
                  onCancel={() => downFileFu(item.thumb)}
                  okText='原图'
                  cancelText='缩略图'
                >
                  <Button size='small' type='text'>
                    下载
                  </Button>
                </Popconfirm>
              ) : (
                <Button
                  size='small'
                  type='text'
                  onClick={() => downFileFu(item.thumb || item.filePath)}
                >
                  下载
                </Button>
              )}
            </>
          )
        }
      }
    ]
  }, [tableBtnFu, downImg])

  // 多选
  const [checkArr, setCheckArr] = useState<number[]>([])

  const checkFu = useCallback(
    (id: number) => {
      if (checkArr.includes(id)) setCheckArr(checkArr.filter(v => v !== id))
      else setCheckArr([...checkArr, id])
    },
    [checkArr]
  )

  const startBtn = useMemo(() => {
    return [
      {
        title: '选择',
        width: 60,
        render: (item: any) => (
          <Checkbox checked={checkArr.includes(item.id)} onChange={() => checkFu(item.id)} />
        )
      }
    ]
  }, [checkArr, checkFu])

  const downsFu = useCallback(
    async (type: 1 | 2) => {
      const res = await A4_APIDownload(checkArr, type)
      if (res.code === 0) {
        MessageFu.success('下载成功')
        downFileFu(res.data, () => {
          setCheckArr([])
        })
      }
    },
    [checkArr]
  )

  useEffect(() => {
    getListFu()
  }, [getListFu, timeKey])

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  return (
    <div className={styles.A4voucher}>
      <div className='pageTitle'>凭证管理</div>

      {/* 第一行 */}
      <div className='C1top'>
        <div className='C1topll C1topllAll'>{searchDom(A4VOUCHER_PARAM_ROWS)}</div>
      </div>

      {/* 第二行 */}
      <div className='C1top C1top2'>
        {downImg['图片'] === '原图和缩略图' ? (
          <Popconfirm
            title='请选择图片规格'
            onConfirm={() => downsFu(1)}
            onCancel={() => downsFu(2)}
            okText='原图'
            cancelText='缩略图'
          >
            <Button type='primary' disabled={checkArr.length === 0}>
              批量下载
            </Button>
          </Popconfirm>
        ) : (
          <Button type='primary' disabled={checkArr.length === 0} onClick={() => downsFu(2)}>
            批量下载
          </Button>
        )}
        &emsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &emsp;
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

      {/* 表格 */}
      <MyTable
        emptyText={true}
        yHeight={580}
        list={tableInfo.list}
        columnsTemp={A4VOUCHER_TABLE_COLUMNS}
        startBtn={startBtn}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoA4voucher = React.memo(A4voucher)

export default MemoA4voucher
