import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input } from 'antd'
import dayjs from 'dayjs'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import { forwardRef, useImperativeHandle } from 'react'
import { FourTableType, TypeB3PageSta } from '../../type'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { B3aForm1 } from '../data'
import { useParams } from 'react-router-dom'
import { statusObj } from '@/utils/tableData'

type Props = {
  info: FourTableType
  pageSta: TypeB3PageSta
  ref: any //当前自己的ref，给父组件调用
  Dom?: React.ReactNode
}

function B3aTop({ info, pageSta, Dom }: Props, ref: any) {
  const { pageKey } = useParams<any>()

  const [formData, setFormData] = useState({} as FourTableType)

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

  const timeChange = useCallback(
    (e: any) => {
      setFormData({ ...formData, date: dayjs(e).format('YYYY-MM-DD') })
    },
    [formData]
  )

  // 上传附件的ref
  const filesRef = useRef<any>(null)

  // 富文本的ref
  const ZRichTextRef = useRef<any>(null)

  // 审批意见的ref
  const ZAuditRef = useRef<any>(null)

  // 审批的sta
  const [auditSta, setAuDitSta] = useState('')

  // 可以让父组件调用子组件的方法
  const resData = useCallback(() => {
    const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }
    // console.log('申请信息富文本', JSON.stringify(rtf1.val || ''))

    const rtf2 = ZAuditRef.current?.resData()
    // console.log('审批信息富文本', rtf2)

    // 上传附件的
    const filesRes = filesRef.current.filesIdRes()

    return { formData, filesRes, rtf1: JSON.stringify(rtf1.val || ''), audit: { rtf2, auditSta } }
  }, [auditSta, formData])

  useImperativeHandle(ref, () => ({
    resData
  }))

  const fileUrl = useMemo(() => {
    return {
      1: 'cms/orderHouse/upload',
      2: 'cms/orderHide/upload',
      3: 'cms/register/upload',
      4: 'cms/orderDel/upload'
    }[pageKey as '1']
  }, [pageKey])

  return (
    <div className={styles.B3aTop} id='B3aTop'>
      {['审批'].includes(pageSta) ? (
        <X3auditInfo
          dirCode={`Four${pageKey}`}
          myUrl={fileUrl}
          auditSta={auditSta}
          auditStaFu={val => setAuDitSta(val)}
          ref={ZAuditRef}
        />
      ) : null}

      <div className='B3aTit'>
        申请信息
        {pageSta !== '新增' ? (
          <Button type='dashed'>{Reflect.get(statusObj, info.status)}</Button>
        ) : null}
      </div>

      <div className='B3aRow'>
        <div className='B3aR1'>
          <div className='B3aRll'>
            <span> * </span>申请名称：
          </div>
          <div className='B3aRrr'>
            <Input
              value={formData.name}
              onChange={e => setFormData({ ...formData, name: e.target.value.trim() })}
              readOnly={['查看', '审批'].includes(pageSta)}
              placeholder='请输入内容'
              maxLength={30}
              showCount
            />
          </div>
        </div>
        <div className='B3aR1'>
          <div className='B3aRll'>
            <span> * </span>业务日期：
          </div>
          <div className='B3aRrr'>
            <DatePicker
              disabled={['查看', '审批'].includes(pageSta)}
              allowClear={false}
              value={dayjs(formData.date)}
              onChange={timeChange}
            />
          </div>
        </div>

        {B3aForm1.map(v => (
          <div className='B3aR1' key={v.name}>
            <div className='B3aRll'>{v.name}：</div>
            <div className='B3aRrr'>
              {formData[v.key as 'name']}
              {['查看', '审批'].includes(pageSta) && v.name === '发起人'
                ? ' - ' + formData.createTime || ''
                : ''}
            </div>
          </div>
        ))}

        <div className='B3aR1 B3aR2'>
          <div className='B3aRll'>附件：</div>
          <div className='B3aRrr'>
            <Z3upFiles
              max={10}
              isLook={['查看', '审批'].includes(pageSta)}
              ref={filesRef}
              fileCheck={false}
              dirCode={`Four${pageKey}`}
              myUrl={fileUrl}
              lookData={info.files || []}
              size={500}
            />
          </div>
        </div>

        <div className='B3aR1'>
          <div className='B3aRll'>原因事由：</div>
          <div className='B3aRrr'>
            <Input
              value={formData.reason}
              onChange={e => setFormData({ ...formData, reason: e.target.value })}
              readOnly={['查看', '审批'].includes(pageSta)}
              placeholder='请输入内容'
              maxLength={30}
              showCount
            />
          </div>
        </div>

        <div className='B3aR1 B3aFull'>
          <div className='B3aRll'>备注：</div>
          <div className='B3aRrr'>
            <ZRichTexts
              check={false}
              dirCode={`Four${pageKey}`}
              myUrl={fileUrl}
              isLook={['查看', '审批'].includes(pageSta)}
              ref={ZRichTextRef}
              isOne={true}
              upAudioBtnNone={true}
            />
          </div>
        </div>
      </div>
      {Dom ? Dom : null}
    </div>
  )
}

export default forwardRef(B3aTop)
