import React, { useCallback, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, DatePicker, Input, Select } from 'antd'
import MyTable from '@/components/MyTable'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { A4voucherSearchType, IA4voucherParams } from './types'
import history, { btnFlagFu } from '@/utils/history'
import {
  A4VOUCHER_PARAM_ROWS,
  A4VOUCHER_TABLE_COLUMNS,
  DEFAULT_A4VOUCHER_PARAMS
} from './constants'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A3_APIList } from '@/store/action/A3flow'

const { RangePicker } = DatePicker

function A4voucher() {
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.F1exhibition.tableInfo)
  const [formData, setFormData] = useState({ ...DEFAULT_A4VOUCHER_PARAMS })
  const formDataRef = useRef({ ...DEFAULT_A4VOUCHER_PARAMS })
  const dispatch = useDispatch()

  // 输入框的改变
  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}
                onChange={(e, dateStrings) => setFormData({ ...formData, [item.key]: dateStrings })}
              />
            ) : 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 = date[0]
      // @ts-ignore
      rest.endTime = date[1]
    }
    dispatch(A3_APIList(rest))
  }, [dispatch])

  // 点击操作按钮
  const tableBtnFu = useCallback((item: any, key: string) => {}, [])

  // 点击删除
  const delTableFu = useCallback(async (item: any) => {}, [])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          let obj = btnFlagFu(item)
          return !Object.values(obj).some(Boolean) ? (
            '-'
          ) : (
            <>
              {obj['编辑'] ? (
                <Button size='small' type='text' onClick={() => tableBtnFu(item, '2')}>
                  编辑
                </Button>
              ) : null}

              {obj['审批'] ? (
                <Button size='small' type='text' onClick={() => tableBtnFu(item, '3')}>
                  审批
                </Button>
              ) : null}
              {obj['查看'] ? (
                <Button size='small' type='text' onClick={() => tableBtnFu(item, '4')}>
                  查看
                </Button>
              ) : null}

              {obj['删除'] ? <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item)} /> : null}
            </>
          )
        }
      }
    ]
  }, [delTableFu, tableBtnFu])

  // 多选
  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])

  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'>
        <Button type='primary'>批量导出</Button>
        &emsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &emsp;
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

      {/* 表格 */}
      <MyTable
        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
