import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import classNames from 'classnames'
import { A1EditInfoType } from '../data'
import { Button, Form, FormInstance, Input, DatePicker, Select } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { A6_APIgetInfo, A6_APIadd, A6_APIedit } from '@/store/action/A6exhibition'
import { MessageFu } from '@/utils/message'
import ZupOne from '@/components/ZupOne'
import MyPopconfirm from '@/components/MyPopconfirm'
import dayjs from 'dayjs'
import ZRichTexts from '@/components/ZRichTexts'
import { A6AddType, A6tableType } from '@/types/api/A6exhibition'

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

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

  // 封面图的ref
  const ZupThumbRef1 = useRef<any>(null)
  // 正文的ref
  const ZRichTextRef = useRef<any>(null)

  // 回显数据的方法调用
  const dataShow = useCallback((info: A6tableType) => {
    let editObj = null
    if (info.status === 0) {
      editObj = {
        ...info,
        title: info.titleB,
        publish: info.publishB,
        remark: info.remarkB,
        context: info.contextB,
        img: info.imgB,
        imgTh: info.imgThB,
        webSite: info.webSiteB
      }
    } else {
      editObj = { ...info }
    }
    FormBoxRef.current?.setFieldsValue({ ...editObj, publish: dayjs(editObj.publish) })

    // 设置封面图
    ZupThumbRef1.current?.setFileComFileFu({
      fileName: '',
      thUrl: editObj.imgTh,
      url: editObj.img
    })

    // 设置正文
    ZRichTextRef.current?.ritxtShowFu({
      txtArr: [
        {
          id: editObj.exhibitId,
          name: '正文',
          txt: editObj.context,
          fileInfo: { fileName: '', filePath: '' }
        }
      ]
    })
  }, [])

  // 编辑 进入页面 获取信息
  const getInfoFu = useCallback(
    async (id: number) => {
      if (editInfo.info) dataShow(editInfo.info)
      else {
        const res = await A6_APIgetInfo(id)
        if (res.code === 0) {
          dataShow(res.data)
        }
      }
    },
    [dataShow, editInfo.info]
  )

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

  // 编辑填入数据
  useEffect(() => {
    if (editInfo.id > 0) {
      getInfoFu(editInfo.id)
    }
  }, [editInfo.id, getInfoFu])

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

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

      const coverUrl1 = ZupThumbRef1.current?.fileComFileResFu()
      const context = ZRichTextRef.current?.fatherBtnOkFu()
      // 没有传 封面图
      if (!coverUrl1.url) return MessageFu.warning('请上传首页封面图!')
      console.log(context)
      if (context.flag) return MessageFu.warning('请输入正文!')

      // 发布
      const obj1: A6AddType = {
        ...values,
        img: coverUrl1.url,
        imgTh: coverUrl1.thUrl,
        context: context.val.txtArr[0].txt,
        publish: values.publish?.format('YYYY-MM-DD') || '',
        publishB: '',
        status: 1,
        titleB: '',
        webSiteB: ''
      }

      // 预发布
      const obj2: A6AddType = {
        img: '',
        imgB: coverUrl1.url,
        imgTh: '',
        imgThB: coverUrl1.thUrl,
        publish: '',
        publishB: values.publish?.format('YYYY-MM-DD') || '',
        status: 0,
        type: values.type,
        title: '',
        titleB: values.title,
        remark: '',
        remarkB: values.remark,
        context: '',
        contextB: context.val.txtArr[0].txt,
        webSiteB: values.webSite,
        webSite: '',
        recommend: values.recommend
      }

      let res: any
      if (btnRef.current === '1') {
        res =
          editInfo.txt === '新增'
            ? await A6_APIadd(obj1)
            : await A6_APIedit({ ...obj1, exhibitId: editInfo.id })
      } else {
        res =
          editInfo.txt === '新增'
            ? await A6_APIadd(obj2)
            : await A6_APIedit({ ...obj2, exhibitId: editInfo.id })
      }

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

  const formOkBtnRef = useRef<any>(null)

  const btnRef = useRef('')

  return (
    <div className={styles.A6add}>
      <div className={classNames('A6aMain')}>
        <Form
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          scrollToFirstError
        >
          <Form.Item
            label='标题'
            name='title'
            rules={[{ required: true, message: '请输入标题！' }]}
          >
            <Input placeholder='请输入内容，最多20个字' maxLength={20} showCount />
          </Form.Item>

          <Form.Item
            label='类型'
            name='type'
            initialValue={1}
            rules={[{ required: true, message: '请选择展览类型！' }]}
          >
            <Select
              defaultValue={1}
              placeholder='请选择展览类型'
              options={[
                { label: '室内展览', value: 1 },
                { label: '室外展览', value: 2 }
              ]}
            />
          </Form.Item>

          <Form.Item
            label='发布日期'
            name='publish'
            rules={[{ required: true, message: '请选择日期！' }]}
            initialValue={dayjs()}
          >
            <DatePicker
              defaultValue={dayjs()}
              allowClear
              placeholder='请选择日期'
              style={{ width: 200 }}
            />
          </Form.Item>

          <Form.Item label='摘要' name='remark'>
            <TextArea maxLength={100} showCount placeholder='请输入内容，最多100字' />
          </Form.Item>

          <Form.Item
            label='推荐展览'
            name='recommend'
            initialValue={1}
            rules={[{ required: true, message: '请选择展览类型！' }]}
          >
            <Select
              defaultValue={1}
              placeholder='请选择展览类型'
              options={[
                { label: '是', value: 1 },
                { label: '否', value: 0 }
              ]}
            />
          </Form.Item>

          <Form.Item
            label={
              <>
                <span style={{ color: 'red' }}>*</span> 正文
              </>
            }
            name='context'
          >
            <ZRichTexts
              check={true}
              dirCode={'A4news'}
              isLook={false}
              ref={ZRichTextRef}
              myUrl='museum/upload/upload'
              isOne={true}
              upAudioBtnNone={true}
            />
          </Form.Item>

          <Form.Item label='虚拟展厅' name='webSite'>
            <Input placeholder='请输入链接' />
          </Form.Item>

          {/* 封面 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              封面图：
            </div>
            <div className='formRight'>
              <ZupOne
                ref={ZupThumbRef1}
                fileCheck={fileCheck}
                size={20}
                dirCode={'A1banner'}
                myUrl='museum/upload/uploadImg'
                format={['image/jpeg', 'image/jpg', 'image/png']}
                inchTxt='2:1'
                formatTxt='png、jpg和jpeg'
                checkTxt='请上传封面图!'
                upTxt='最多1张'
                myType='thumb'
              />
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='A6abtn'>
            <div className='A6abtnBox'>
              <Button
                type='primary'
                htmlType='submit'
                onClick={() => {
                  btnRef.current = '1'
                  formOkBtnRef.current?.click()
                }}
              >
                发布
              </Button>
              <Button
                type='primary'
                htmlType='submit'
                onClick={() => {
                  btnRef.current = '0'
                  formOkBtnRef.current?.click()
                }}
              >
                预发布
              </Button>
              <MyPopconfirm txtK='取消' onConfirm={closeFu} />
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

const MemoA6add = React.memo(A6add)

export default MemoA6add
