import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import dayjs from 'dayjs'
import ZRichTexts from '@/components/ZRichTexts'
import { A1Tab1ListType } from '..'
import { MessageFu } from '@/utils/message'
import { A1_APIsaveTab1 } from '@/store/action/A1record'

type Props = {
  sId: number
  sInfo: A1Tab1ListType
  closeFu: () => void
  upTableFu: () => void
}

function A1tab1add({ sInfo, closeFu, upTableFu, sId }: Props) {
  // 富文本的ref
  const ZRichTextRef = useRef<any>(null)

  const [date, setDate] = useState('')

  useEffect(() => {
    if (sInfo.id > 0) {
      setDate(sInfo.date)
      // 设置富文本
      if (sInfo.rtf) ZRichTextRef.current?.ritxtShowFu(JSON.parse(sInfo.rtf))
    }
  }, [sInfo])

  const addBtn = useCallback(async () => {
    // 富文本
    const rtf = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

    if (!date) return MessageFu.warning('请选择日期')

    const obj = {
      id: sInfo.id > 0 ? sInfo.id : null,
      date,
      martyrId: sId,
      rtf: JSON.stringify(rtf.val || '')
    }
    const res = await A1_APIsaveTab1(obj)
    if (res.code === 0) {
      MessageFu.success(sInfo.id > 0 ? '编辑成功' : '新增成功')
      upTableFu()
      closeFu()
    }
  }, [closeFu, date, sId, sInfo.id, upTableFu])

  return (
    <Modal
      wrapClassName={styles.A1tab1add}
      open={true}
      title={sInfo.id > 0 ? '编辑生平' : '新增生平'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='A1t1Amain'>
        <div className='A1T1Arow'>
          <div>
            <span>* </span> 日期：
          </div>
          <div>
            <DatePicker
              value={date ? dayjs(date) : null}
              onChange={e => (e ? setDate(dayjs(e).format('YYYY-MM-DD')) : '')}
            />
          </div>
        </div>

        <div className='A1T1Arow'>
          <div>简介：</div>
          <div>
            <ZRichTexts
              check={false}
              dirCode='A1tab1life'
              myUrl='cms/life/upload'
              isLook={false}
              ref={ZRichTextRef}
              isOne={true}
              upAudioBtnNone={true}
              imgOne
            />
          </div>
        </div>
      </div>

      <div className='A1T1Abtn'>
        <Button type='primary' onClick={addBtn}>
          提交
        </Button>
        &emsp;
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
      </div>
    </Modal>
  )
}

const MemoA1tab1add = React.memo(A1tab1add)

export default MemoA1tab1add
