import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import A1look from './A1look'
import { useDispatch, useSelector } from 'react-redux'
import { A1_APIdel, A1_APIgetList } from '@/store/action/A1record'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { Button, Input, Table } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A1ListType, jiGuanFu, LookInfoType } from './data'
import A1add from './A1add'
import ImageLazy from '@/components/ImageLazy'

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

function A1record() {
  const dispatch = useDispatch()

  const [fromData, setFromData] = useState(baseFromData)

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

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

  // 作品名称的输入
  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 tableInfo = useSelector((state: RootState) => state.A1record.tableInfo)

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

  // 点击查看
  const [lookInfo, setLookInfo] = useState<LookInfoType>({
    id: 0,
    txt: ''
  })

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

  // 表格相关
  const columns = useMemo(() => {
    const arr: any = [
      { title: 'ID', dataIndex: 'num', width: 100 },
      {
        title: '封面图',
        width: 80,
        render: (item: A1ListType) => (
          <div className='tableImgAuto'>
            <ImageLazy
              width={60}
              height={60}
              src={item.thumb || item.thumbPc}
              srcBig={item.thumbPc || item.thumb}
            />
          </div>
        )
      },
      { title: '姓名', render: (item: A1ListType) => item.name, width: 100 },
      {
        title: '性别',
        width: 100,
        render: (item: A1ListType) => (item.gender === 1 ? '男' : '女')
      },
      { title: '民族', width: 100, render: (item: A1ListType) => item.nation || '（空）' },
      { title: '番号', render: (item: A1ListType) => item.intro || '（空）' },
      {
        title: '籍贯',

        render: (item: A1ListType) => jiGuanFu(item)
      },
      {
        title: '生卒',
        width: 200,
        render: (item: A1ListType) =>
          (item.dateStart || '（空）') + ' ~ ' + (item.dateEnd || '（空）')
      },

      {
        title: '备注',
        render: (item: A1ListType) =>
          item.remark ? (
            item.remark.length >= 50 ? (
              <span style={{ cursor: 'pointer' }} title={item.remark}>
                {item.remark.substring(0, 50) + '...'}
              </span>
            ) : (
              item.remark
            )
          ) : (
            '（空）'
          )
      },
      { title: '编辑时间', width: 150, render: (item: A1ListType) => item.updateTime },
      { title: '编辑人', width: 100, render: (item: A1ListType) => item.creatorName },

      {
        title: '操作',
        fixed: 'right',
        width: 150,
        render: (item: A1ListType) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={() => setLookInfo({ id: item.id, txt: '查看' })}
            >
              查看
            </Button>
            <Button
              size='small'
              type='text'
              onClick={() => setLookInfo({ id: item.id, txt: '编辑' })}
            >
              编辑
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
    return arr
  }, [delTableFu])

  return (
    <div className={styles.A1record}>
      <div className='pageTitle'>
        烈士档案{lookInfo.txt ? ` - ${lookInfo.txt}` : ''}{' '}
        {lookInfo.txt === '查看' ? (
          <div onClick={() => setLookInfo({ id: 0, txt: '' })} className='A1LookBack'>
            <Button>返回</Button>
          </div>
        ) : null}
      </div>

      {/* 顶部筛选 */}
      <div className='A1top'>
        <div className='A1topLeft'>
          <div>
            <Input
              key={inputKey}
              maxLength={30}
              showCount
              style={{ width: 300 }}
              placeholder='请输入ID/姓名/番号/籍贯'
              allowClear
              onChange={e => fromKeyChangeFu(e, 'searchKey')}
            />
          </div>
        </div>

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

      {/* 表格主体 */}
      <div className='A1tableBox'>
        <Table
          scroll={{ x: 'max-content', y: 645 }}
          columns={columns}
          dataSource={tableInfo.list}
          rowKey='id'
          pagination={{
            showQuickJumper: true,
            position: ['bottomCenter'],
            showSizeChanger: true,
            current: fromData.pageNum,
            pageSize: fromData.pageSize,
            total: tableInfo.total,
            onChange: (pageNum, pageSize) => setFromData({ ...fromData, pageNum, pageSize })
          }}
        />
      </div>

      {['新增', '编辑'].includes(lookInfo.txt) ? (
        <A1add
          sId={lookInfo.id}
          closeFu={() => setLookInfo({ id: 0, txt: '' })}
          addTableFu={resetSelectFu}
          upTableFu={getListFu}
        />
      ) : null}

      {lookInfo.txt === '查看' ? <A1look sId={lookInfo.id} /> : null}
    </div>
  )
}

const MemoA1record = React.memo(A1record)

export default MemoA1record
