import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { A1ListSelectType, A1ListType } from '../A1record/data'
import { A1_APIgetList } from '@/store/action/A1record'
import { A4_APIdel, A4_APIgetList } from '@/store/action/A4antique'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { Button, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { A4tableC } from '@/utils/tableData'
import A4add from './A4add'

const baseFromData = {
  pageNum: 1,
  pageSize: 10,
  searchKey: '',
  martyrId: ''
}

function A4antique() {
  const dispatch = useDispatch()

  // 获取所有烈士信息
  const [listAllRes, setListAllRes] = useState<A1ListSelectType>([])

  const getListAllFu = useCallback(async () => {
    const res = await A1_APIgetList(
      {
        pageNum: 1,
        pageSize: 99999
      },
      true
    )
    if (res.code === 0) {
      const list: A1ListType[] = res.data.records || []
      setListAllRes(
        list.map(c => ({
          value: c.id,
          label: c.name
        }))
      )
    }
  }, [])

  useEffect(() => {
    getListAllFu()
  }, [getListAllFu])
  // 获取所有烈士信息-end

  const [fromData, setFromData] = useState(baseFromData)

  const getListFu = useCallback(() => {
    dispatch(A4_APIgetList(fromData))
  }, [dispatch, fromData])

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

  const tableInfo = useSelector((state: RootState) => state.A4antique.tableInfo)

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setInputKey(Date.now())
    setFromData({ ...baseFromData })
  }, [])

  // 下拉框的改变
  const selectChangeFu = useCallback(
    (value: any, key: 'martyrId') => {
      setFromData({ ...fromData, [key]: value, pageNum: 1 })
    },
    [fromData]
  )

  // 作品名称的输入
  const timeRef = useRef(-1)
  const [inputKey, setInputKey] = useState(0)
  const fromKeyChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: 'searchKey') => {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setFromData({ ...fromData, [key]: e.target.value, pageNum: 1 })
      }, 500)
    },
    [fromData]
  )

  // 点击新增、编辑
  const [editId, setEditId] = useState(0)

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A4_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

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

  return (
    <div className={styles.A4antique}>
      <div className='pageTitle'>烈士档案{editId ? (editId > 0 ? ' - 编辑' : ' - 新增') : ''}</div>
      {/* 顶部筛选 */}
      <div className='A4top'>
        <div className='A4topLeft'>
          <div>
            <Input
              key={inputKey}
              maxLength={30}
              showCount
              style={{ width: 300 }}
              placeholder='请输入文件名称'
              allowClear
              onChange={e => fromKeyChangeFu(e, 'searchKey')}
            />
          </div>

          <div>
            <Select
              style={{ width: 240 }}
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              allowClear
              placeholder='搜索并选择关联烈士'
              showSearch
              options={listAllRes}
              value={fromData.martyrId || null}
              onChange={e => selectChangeFu(e, 'martyrId')}
            />
          </div>
        </div>

        <div>
          <Button onClick={resetSelectFu}>重置</Button>
          &emsp;
          <Button type='primary' onClick={() => setEditId(-1)}>
            新增
          </Button>
        </div>
      </div>

      {/* 表格主体 */}
      <div className='A4tableBox'>
        <MyTable
          yHeight={645}
          list={tableInfo.list}
          columnsTemp={A4tableC}
          lastBtn={tableLastBtn}
          pageNum={fromData.pageNum}
          pageSize={fromData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => setFromData({ ...fromData, pageNum, pageSize })}
        />
      </div>
      {editId ? (
        <A4add
          sId={editId}
          closeFu={() => setEditId(0)}
          addTableFu={resetSelectFu}
          upTableFu={getListFu}
          listAllRes={listAllRes}
        />
      ) : null}
    </div>
  )
}

const MemoA4antique = React.memo(A4antique)

export default MemoA4antique
