import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import { TypeB3Form } from './type'
import { useDispatch, useSelector } from 'react-redux'
import { Z5_APIgetList } from '@/store/action/Z5role'
import { RootState } from '@/store'
import dayjs from 'dayjs'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B3tableC } from '@/utils/tableData'
const { RangePicker } = DatePicker

type InputKeyType = 'aaaa' | 'bbbb' | 'cccc' | 'dddd'

const inputKeyArr: {
  name: string
  key: InputKeyType
}[] = [
  { name: '申请编号', key: 'aaaa' },
  { name: '业务名称', key: 'bbbb' },
  { name: '发起部门', key: 'cccc' },
  { name: '发起人', key: 'dddd' }
]

const baseFormData: TypeB3Form = {
  pageSize: 10,
  pageNum: 1,
  aaaa: '',
  bbbb: '',
  cccc: '',
  dddd: '',
  startTime: '',
  endTime: '',
  eeee: '',
  ffff: ''
}

type Props = {
  pageSta: '入馆' | '入藏'
}

// 没有接入后端 待完善

function B34page({ pageSta }: Props) {
  // 角色
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(
      Z5_APIgetList({
        pageNum: 1,
        pageSize: 99999,
        searchKey: ''
      })
    )
  }, [dispatch])

  const { list: roleList } = useSelector((state: RootState) => state.Z5role.tableInfo)

  const [formData, setFormData] = useState(baseFormData)
  const formDataRef = useRef(baseFormData)

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

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

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

  // 时间选择器改变
  const timeChange = useCallback(
    (date: any, dateString: any) => {
      let startTime = ''
      let endTime = ''
      if (dateString[0] && dateString[1]) {
        startTime = dateString[0] + ' 00:00:00'
        endTime = dateString[1] + ' 23:59:59'
      }
      setFormData({ ...formData, startTime, endTime })
    },
    [formData]
  )

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    console.log('发送请求', formDataRef.current)
  }, [])

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

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

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

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

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      getListFu()
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          return (
            <>
              <Button size='small' type='text'>
                编辑
              </Button>
              <Button size='small' type='text'>
                审批
              </Button>
              <Button size='small' type='text'>
                查看
              </Button>
              <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
            </>
          )
        }
      }
    ]
  }, [delTableFu])

  return (
    <div className={styles.B34page}>
      <div className='pageTitle'>藏品{pageSta}</div>

      <div className='B3top'>
        <div className='B3topll'>
          {inputKeyArr.map(item => (
            <div key={item.name}>
              <span>{item.name}：</span>
              <Input
                placeholder={`请输入${item.name}`}
                maxLength={30}
                value={formData[item.key]}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            </div>
          ))}
        </div>
        <div className='B3toprr'>
          <Button type='primary'>批量导出</Button>&emsp;<Button type='primary'>新增</Button>
        </div>
      </div>
      <div className='B3top'>
        <div className='B3topll'>
          <div>
            <span>发起日期范围：</span>
            <RangePicker
              value={
                formData.startTime ? [dayjs(formData.startTime), dayjs(formData.endTime)] : null
              }
              onChange={timeChange}
            />
          </div>

          <div>
            <span>申请状态：</span>
            <Select
              placeholder='请选择'
              style={{ width: 200 }}
              value={formData.eeee}
              onChange={e => setFormData({ ...formData, eeee: e })}
              options={[{ value: '', label: '全部' }]}
            />
          </div>

          <div>
            <span>选择角色：</span>
            <Select
              style={{ width: 200 }}
              placeholder='请选择'
              options={[{ id: '', roleName: '全部' }, ...roleList.filter(v => v.id !== 1)]}
              fieldNames={{ value: 'id', label: 'roleName' }}
              value={formData.ffff}
              onChange={e => setFormData({ ...formData, ffff: e })}
            />
          </div>
        </div>
        <div className='B3toprr'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;<Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={610}
        list={[{ id: 1 }]}
        columnsTemp={B3tableC}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={0}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoB34page = React.memo(B34page)

export default MemoB34page
