import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { Button, Cascader, DatePicker, Input, Select } from 'antd'
import { A3_APIList } from '@/store/action/A3flow'
import history, { btnFlagFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import {
  C21WEALTH_PARAM_ROWS,
  C21WEALTH_TABLE_COLUMNS,
  DEFAULT_C21WEALTH_PARAMS
} from './constants'
import { C21WealthSearchType, IC21WealthParams } from './types'

const { RangePicker } = DatePicker

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

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

  // 顶部筛选
  const searchDom = useCallback(
    (arr: C21WealthSearchType[]) => {
      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 })}
              />
            ) : (
              <Cascader
                options={item.data}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={
                  formData[item.key as 'num']
                    ? (formData[item.key as 'num'] as string).split(',')
                    : []
                }
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </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_C21WEALTH_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])

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

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

  return (
    <div className={styles.C21wealth}>
      <div className='pageTitle'>资源使用</div>

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

      {/* 第二行 */}
      <div className='C1top C1top2'>
        <Button type='primary'>批量导出</Button>
        &emsp;
        <Button type='primary' onClick={() => history.push('/wealth_edit/1/null')}>
          新增
        </Button>
        &emsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &emsp;
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

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

const MemoC21wealth = React.memo(C21wealth)

export default MemoC21wealth
