import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A3EditInfoType } from '../type'
import { Button, Form, FormInstance, Input, InputNumber, Select } from 'antd'
import classNames from 'classnames'
import { A3_APIgetInfo, A3_APIgetTypeList, A3_APIsave } from '@/store/action/A3course'
import TextArea from 'antd/es/input/TextArea'
import MyPopconfirm from '@/components/MyPopconfirm'
import ZRichTexts from '@/components/ZRichTexts'
import { MessageFu } from '@/utils/message'

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

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

  // 课程类别数组
  const [list, setList] = useState<any>([])

  const getListFu = useCallback(async () => {
    const res = await A3_APIgetTypeList()
    if (res.code === 0) {
      const data: any = res.data
      setList(
        data.map((v: any) => ({
          label: v.name,
          value: v.id
        }))
      )
    }
  }, [])

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

  // 富文本的ref
  const ZRichTextRef1 = useRef<any>(null)
  const ZRichTextRef2 = useRef<any>(null)
  const ZRichTextRef3 = useRef<any>(null)

  //  获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A3_APIgetInfo(id)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue(res.data)
      ZRichTextRef1.current?.ritxtShowFu(JSON.parse(res.data.introRtf || '{}'))
      ZRichTextRef2.current?.ritxtShowFu(JSON.parse(res.data.teamRtf || '{}'))
      ZRichTextRef3.current?.ritxtShowFu(JSON.parse(res.data.infoRtf || '{}'))
    }
  }, [])

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

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 富文本校验不通过
      const rtf1 = ZRichTextRef1.current?.fatherBtnOkFu() || { flag: true }
      const rtf2 = ZRichTextRef2.current?.fatherBtnOkFu() || { flag: true }
      const rtf3 = ZRichTextRef3.current?.fatherBtnOkFu() || { flag: true }

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        introRtf: rtf1.val,
        teamRtf: rtf2.val,
        infoRtf: rtf3.val
      }
      const res = await A3_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.A3add}>
      <div className={classNames('A3aMain', editInfo.txt === '查看' ? 'A3aMainLook' : '')}>
        <Form
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          scrollToFirstError
        >
          <Form.Item
            label='课程类别'
            name='dictTypeId'
            rules={[{ required: true, message: '请选择课程类别!' }]}
          >
            <Select allowClear placeholder='请选择' style={{ width: 200 }} options={list} />
          </Form.Item>

          <Form.Item
            label='课程名称'
            name='name'
            rules={[{ required: true, message: '请输入课程名称!' }]}
            getValueFromEvent={e => e.target.value.trim()}
          >
            <Input
              readOnly={editInfo.txt === '查看'}
              placeholder='请输入内容'
              maxLength={20}
              showCount
            />
          </Form.Item>

          <Form.Item label='课堂简介' name='intro'>
            <TextArea
              readOnly={editInfo.txt === '查看'}
              maxLength={100}
              showCount
              placeholder='请输入内容概要'
            />
          </Form.Item>

          <div className='formRow'>
            <div className='formLeft'></div>
            <div className='formRight'>
              <ZRichTexts
                check={false}
                dirCode={'A2xuZhiText'}
                isLook={editInfo.txt === '查看'}
                ref={ZRichTextRef1}
                myUrl='cms/subject/upload'
                isOne={true}
                upAudioBtnNone={true}
                otherArr={[{ key: 'moduleName', value: 'apply' }]}
              />
            </div>
          </div>

          <Form.Item label='授课团队' name='team'>
            <TextArea
              readOnly={editInfo.txt === '查看'}
              maxLength={100}
              showCount
              placeholder='请输入内容概要'
            />
          </Form.Item>

          <div className='formRow'>
            <div className='formLeft'></div>
            <div className='formRight'>
              <ZRichTexts
                check={false}
                dirCode={'A2xuZhiText'}
                isLook={editInfo.txt === '查看'}
                ref={ZRichTextRef2}
                myUrl='cms/subject/upload'
                isOne={true}
                upAudioBtnNone={true}
                otherArr={[{ key: 'moduleName', value: 'apply' }]}
              />
            </div>
          </div>

          <Form.Item label='预约须知' name='info'>
            <TextArea
              readOnly={editInfo.txt === '查看'}
              maxLength={100}
              showCount
              placeholder='请输入内容概要'
            />
          </Form.Item>

          <div className='formRow'>
            <div className='formLeft'></div>
            <div className='formRight'>
              <ZRichTexts
                check={false}
                dirCode={'A2xuZhiText'}
                isLook={editInfo.txt === '查看'}
                ref={ZRichTextRef3}
                myUrl='cms/subject/upload'
                isOne={true}
                upAudioBtnNone={true}
                otherArr={[{ key: 'moduleName', value: 'apply' }]}
              />
            </div>
          </div>

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

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

const MemoA3add = React.memo(A3add)

export default MemoA3add
