import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A1EditInfoType } from '@/pages/A1goods/data'
import { Button, Form, FormInstance, Input, InputNumber } from 'antd'
import { A4_APIgetInfo, A4_APIsave } from '@/store/action/A4video'
import { MessageFu } from '@/utils/message'
import classNames from 'classnames'
import ZupOne from '@/components/ZupOne'
import TextArea from 'antd/es/input/TextArea'
import MyPopconfirm from '@/components/MyPopconfirm'

type Props = {
  editInfo: A1EditInfoType
  closeFu: () => void
  addTableFu: () => void
  editTableFu: () => void
}

function A4add({ editInfo, closeFu, addTableFu, editTableFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 封面图的ref
  const ZupThumbRef = useRef<any>(null)

  // 附件的ref
  const ZupVideoRef = useRef<any>(null)

  // 编辑/查看 进入页面 获取信息
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A4_APIgetInfo(id)
    if (res.code === 0) {
      const info = res.data
      const obj = {
        ...info
      }

      FormBoxRef.current?.setFieldsValue(obj)

      // 设置封面图
      ZupThumbRef.current?.setFileComFileFu({
        fileName: '',
        filePath: info.thumb
      })

      // 设置附件
      ZupVideoRef.current?.setFileComFileFu({
        fileName: info.fileName,
        filePath: info.filePath
      })
    }
  }, [])

  // 附件 是否 已经点击过确定
  const [fileCheck, setFileCheck] = useState(false)

  useEffect(() => {
    if (editInfo.id > 0) {
      getInfoFu(editInfo.id)
    } else {
      FormBoxRef.current?.setFieldsValue({
        sort: 999
      })
    }
  }, [editInfo.id, getInfoFu])

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFileCheck(true)
  }, [])

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true)
      const coverUrl1 = ZupThumbRef.current?.fileComFileResFu()
      // 没有传 封面图
      if (!coverUrl1.filePath) return

      // 没有传视频附件
      let fileName = ''
      let filePath = ''
      // txt附件
      const ZupVideoRefObj = ZupVideoRef.current?.fileComFileResFu()
      fileName = ZupVideoRefObj.fileName
      filePath = ZupVideoRefObj.filePath
      if (!filePath) return MessageFu.warning('请上传附件!')

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        thumb: coverUrl1.filePath,
        fileName,
        filePath
      }

      const res = await A4_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(editInfo.txt + '成功!')
        editInfo.id > 0 ? editTableFu() : addTableFu()
        closeFu()
      }
    },
    [addTableFu, closeFu, editInfo.id, editInfo.txt, editTableFu]
  )

  return (
    <div className={styles.A4add}>
      <div className={classNames('A4aMain', editInfo.txt === '查看' ? 'A4aMainLook' : '')}>
        <Form
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          scrollToFirstError
        >
          <Form.Item label='名称' name='name' rules={[{ required: true, message: '请输入名称!' }]}>
            <Input
              readOnly={editInfo.txt === '查看'}
              placeholder='请输入内容'
              maxLength={20}
              showCount
            />
          </Form.Item>

          {/* 封面 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              封面：
            </div>
            <div className='formRight'>
              <ZupOne
                ref={ZupThumbRef}
                isLook={editInfo.txt === '查看'}
                fileCheck={fileCheck}
                size={5}
                dirCode={'A2video'}
                myUrl='cms/video/upload'
                format={['image/jpeg', 'image/png']}
                formatTxt='png、jpg和jpeg'
                checkTxt='请上传封面图!'
                upTxt='最多1张'
                myType='thumb'
              />
            </div>
          </div>
          {editInfo.txt === '查看' ? <br /> : null}

          {/* 附件 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              附件：
            </div>
            <div className='formRight'>
              <ZupOne
                ref={ZupVideoRef}
                isLook={editInfo.txt === '查看'}
                fileCheck={fileCheck}
                size={200}
                dirCode='A2video'
                myUrl='cms/video/upload'
                format={['video/mp4']}
                formatTxt='mp4'
                checkTxt='请上传mp4附件!'
                upTxt='最多1个'
                myType='video'
              />
            </div>
          </div>
          {editInfo.txt === '查看' ? <br /> : null}

          <Form.Item label='简介' name='remark'>
            <TextArea
              readOnly={editInfo.txt === '查看'}
              maxLength={200}
              showCount
              placeholder='请输入内容'
            />
          </Form.Item>

          <div className='A4fromRow'>
            <Form.Item
              label='排序值'
              name='sort'
              rules={[{ required: true, message: '请输入排序值!' }]}
            >
              <InputNumber min={1} max={999} precision={0} placeholder='请输入' />
            </Form.Item>
            <div className='A4_6Frow' hidden={editInfo.txt === '查看'}>
              请输入1~999的数字。数字越小，排序越靠前。数字相同时，更新发布的内容排在前面
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='A4abtn'>
            {editInfo.txt === '查看' ? (
              <Button onClick={closeFu}>返回</Button>
            ) : (
              <>
                <Button type='primary' htmlType='submit'>
                  提交
                </Button>
                <br />
                <br />
                <MyPopconfirm txtK='取消' onConfirm={closeFu} />
              </>
            )}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

const MemoA4add = React.memo(A4add)

export default MemoA4add
