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

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

function A4add({ editInfo, closeFu, editTableFu, addTableFu }: Props) {
  const [dirCode, setDirCode] = useState('')

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

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

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

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

      setDirCode(data.dirCode)

      // 设置富文本
      ZRichTextRef.current?.ritxtShowFu(JSON.parse(data.rtf))

      const obj = {
        ...data,
        myTime: dayjs(data.datePublish),
        myTimeSta: dayjs(data.dateStart)
      }

      if (data.dateEnd) {
        obj.myTimeEnd = dayjs(data.dateEnd)
      }

      FormBoxRef.current?.setFieldsValue(obj)

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

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

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true)

      const coverUrl1 = ZupThumbRef.current?.fileComFileResFu()
      // 没有传 封面图
      if (!coverUrl1.filePath) return MessageFu.warning('请上传封面图!')

      // 发布日期
      const datePublish = dayjs(values.myTime).format('YYYY-MM-DD')

      // 开始时间
      const dateStart = dayjs(values.myTimeSta).format('YYYY-MM-DD HH:mm')

      // 结束时间(可能为空)
      let dateEnd = ''
      if (values.myTimeEnd) dateEnd = dayjs(values.myTimeEnd).format('YYYY-MM-DD HH:mm')

      // 富文本校验不通过
      const rtf = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

      if (rtf.flag) return MessageFu.warning('请输入完整正文!')

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        datePublish,
        thumb: coverUrl1.filePath,
        rtf: JSON.stringify(rtf.val || ''),
        dirCode,
        dateStart,
        dateEnd
      }

      // if (obj) {
      //   console.log(123, obj);
      //   return;
      // }

      const res = await A4_APIsave(obj)

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

  useEffect(() => {
    if (editInfo.id > 0) {
      getInfoFu(editInfo.id)
    } else {
      setDirCode(Date.now() + '')
      FormBoxRef.current?.setFieldsValue({
        myTime: dayjs(Date.now()),
        sort: 999,
        display: 1
      })
    }
  }, [editInfo.id, getInfoFu])

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

          <Form.Item label='板块' name='type' rules={[{ required: true, message: '请选择板块!' }]}>
            <Select
              placeholder='请选择板块'
              style={{ width: 200 }}
              options={A4Selct_1.filter(v => v.label !== '全部')}
            />
          </Form.Item>

          <Form.Item
            label='开始时间'
            name='myTimeSta'
            rules={[{ required: true, message: '请选择开始时间!' }]}
          >
            <DatePicker showTime format={'YYYY-MM-DD HH:mm'} placeholder='请选择开始时间' />
          </Form.Item>

          <Form.Item label='结束时间' name='myTimeEnd'>
            <DatePicker showTime format={'YYYY-MM-DD HH:mm'} placeholder='请选择结束时间' />
          </Form.Item>

          <Form.Item
            label='地点'
            name='address'
            rules={[{ required: true, message: '请输入标题!' }]}
          >
            <TextArea
              readOnly={editInfo.txt === '查看'}
              placeholder='请输入内容'
              maxLength={100}
              showCount
            />
          </Form.Item>

          <Form.Item
            label='人数限制'
            name='remark'
            rules={[{ required: true, message: '请输入标题!' }]}
          >
            <TextArea
              readOnly={editInfo.txt === '查看'}
              placeholder='请输入内容'
              maxLength={100}
              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={dirCode}
                myUrl='cms/learn/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'>
              <ZRichTexts
                check={fileCheck}
                dirCode={dirCode}
                isLook={editInfo.txt === '查看'}
                ref={ZRichTextRef}
                myUrl='cms/learn/upload'
                isOne={true}
                upAudioBtnNone={true}
              />
            </div>
          </div>

          <Form.Item
            label='发布日期'
            name='myTime'
            rules={[{ required: true, message: '请选择发布日期!' }]}
          >
            <DatePicker />
          </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
            label='状态'
            name='display'
            rules={[{ required: true, message: '请选择状态!' }]}
          >
            <Select
              placeholder='请选择状态'
              style={{ width: 149 }}
              options={[
                { value: 1, label: '发布' },
                { value: 0, label: '不发布' }
              ]}
            />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <Form.Item className='A4Ebtn'>
            {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
