import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Button, Empty } from 'antd'
import { A1_APIdelTab1, A1_APIgetTab1List } from '@/store/action/A1record'
import A1tab1add from './A1tab1add'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { textFu } from '@/utils/history'

export type A1Tab1ListType = {
  id: number
  date: string
  rtf: string
}

type Props = {
  sId: number
}

function A1tab1life({ sId }: Props) {
  const [data, setData] = useState<{ list: A1Tab1ListType[]; flag: boolean }>({
    list: [],
    flag: false
  })

  const getInfoFu = useCallback(async () => {
    const res = await A1_APIgetTab1List(sId)
    if (res.code === 0) {
      setData({ list: res.data || [], flag: true })
    }
  }, [sId])

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

  const [addInfo, setAddInfo] = useState({} as A1Tab1ListType)

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

  return (
    <div className={styles.A1tab1life}>
      <div className='A1t1btn'>
        <Button type='primary' onClick={() => setAddInfo({ id: -1 } as A1Tab1ListType)}>
          新增生平
        </Button>
      </div>

      {data.flag && data.list.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <>
          {data.list.map(item => (
            <div className='A1t1Row' key={item.id}>
              <div className='A1t1Row1'>
                <div>日期：</div>
                <div>{item.date}</div>
                <div className='A1t1Row1Btn'>
                  <Button size='small' type='text' onClick={() => setAddInfo(item)}>
                    编辑
                  </Button>
                  <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
                </div>
              </div>

              <div className='A1t1Row1'>
                <div>简介：</div>
                <div dangerouslySetInnerHTML={{ __html: textFu(item.rtf) || '（空）' }}></div>
              </div>
            </div>
          ))}
        </>
      )}
      {addInfo.id ? (
        <A1tab1add
          sId={sId}
          sInfo={addInfo}
          closeFu={() => setAddInfo({} as A1Tab1ListType)}
          upTableFu={getInfoFu}
        />
      ) : null}
    </div>
  )
}

const MemoA1tab1life = React.memo(A1tab1life)

export default MemoA1tab1life
