import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { Button, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A1_APIlogDel, A1_APIlogGetList } from '@/store/action/A1record'
import { MessageFu } from '@/utils/message'
import MyTable from '@/components/MyTable'
import A1T3add, { A3T3addInfoType } from './A1T3add'

type ListType = {
  id: number
  dictId: number
}

type FromDataType = {
  dictId: number | null
  searchKey: string
  type: string | null
}

const baseFromData: FromDataType = {
  dictId: null,
  searchKey: '',
  type: null
}

type Props = {
  sId: number
}

function A1tab3log({ sId }: Props) {
  const listObj = useSelector((state: RootState) => state.A3dict.listObj)

  const [fromData, setFromData] = useState(baseFromData)

  const [list, setList] = useState<ListType[]>([])

  const getListFu = useCallback(async () => {
    const res = await A1_APIlogGetList({ ...fromData, bridgeId: sId, pageNum: 1, pageSize: 99999 })

    if (res.code === 0) {
      setList(res.data || [])
    }
  }, [fromData, sId])

  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 })
      }, 500)
    },
    [fromData]
  )

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

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

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

  const staBtn = useMemo(() => {
    return [
      {
        title: '维护类型',
        render: (item: ListType) => listObj.maintain.find(v => v.id === item.dictId)?.name
      }
    ]
  }, [listObj.maintain])

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

  // 新增编辑、查看
  const [addInfo, setAddInfo] = useState({} as A3T3addInfoType)

  return (
    <div className={styles.A1tab3log}>
      <div className='A1T3top'>
        <div className='A1T3top1'>
          <div>
            <Input
              key={inputKey}
              maxLength={50}
              showCount
              style={{ width: 400 }}
              placeholder='请输入维护详情'
              allowClear
              onChange={e => fromKeyChangeFu(e, 'searchKey')}
            />
          </div>

          <div>
            <Select
              allowClear
              style={{ width: 200 }}
              placeholder='维护类型'
              value={fromData.dictId || null}
              onChange={e => selectChangeFu(e, 'dictId')}
              options={listObj.maintain.map(v => ({ value: v.id, label: v.name }))}
            />
          </div>
        </div>
        <div className='A1T3top2'>
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button type='primary' onClick={() => setAddInfo({ txt: '新增', id: -1 })}>
            新增
          </Button>
        </div>
      </div>

      <MyTable
        classKey='A1tab3file'
        list={list}
        columnsTemp={[
          ['text', '维护详情', 'intro', 50],
          ['txt', '编辑人', 'creatorName'],
          ['txt', '编辑时间', 'updateTime']
        ]}
        staBtn={staBtn}
        lastBtn={tableLastBtn}
        pagingInfo={false}
        widthSet={{ intro: 700 }}
      />

      {addInfo.txt ? (
        <A1T3add
          addInfo={addInfo}
          closeFu={() => setAddInfo({ txt: '', id: 0 })}
          upTableFu={getListFu}
          bridgeId={sId}
        />
      ) : null}
    </div>
  )
}

const MemoA1tab3log = React.memo(A1tab3log)

export default MemoA1tab3log
