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 } from 'antd'
import { A1_APIgetInfo, A1_APIadd, A1_APIedit } from '@/store/action/A1banner'
import { MessageFu } from '@/utils/message'
import ZupOne from '@/components/ZupOne'
import { A1AddType, A1tbType } from '@/types'
import MyPopconfirm from '@/components/MyPopconfirm'
import dayjs from 'dayjs'

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

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

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

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

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

  // 编辑 进入页面 获取信息
  const getInfoFu = useCallback(
    async (id: number) => {
      if (editInfo.info) dataShow(editInfo.info)
      else {
        const res = await A1_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 coverUrl = ZupThumbRef.current?.fileComFileResFu()
      // 没有传 封面图
      if (!coverUrl.url) return MessageFu.warning('请上传封面图!')

      // 发布
      const obj1: A1AddType = {
        ...values,
        img: coverUrl.url,
        imgB: '',
        imgTh: coverUrl.thUrl,
        imgThB: '',
        publish: values.publish?.format('YYYY-MM-DD') || '',
        publishB: '',
        status: 1,
        titleB: '',
        urlB: ''
      }

      // 预发布
      const obj2: A1AddType = {
        img: '',
        imgB: coverUrl.url,
        imgTh: '',
        imgThB: coverUrl.thUrl,
        publish: '',
        publishB: values.publish?.format('YYYY-MM-DD') || '',
        status: 0,
        title: '',
        titleB: values.title,
        url: '',
        urlB: values.url
      }

      let res: any
      if (btnRef.current === '1') {
        res =
          editInfo.txt === '新增'
            ? await A1_APIadd(obj1)
            : await A1_APIedit({ ...obj1, carouselId: editInfo.id })
      } else {
        res =
          editInfo.txt === '新增'
            ? await A1_APIadd(obj2)
            : await A1_APIedit({ ...obj2, carouselId: 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.A1add}>
      <div className={classNames('A1aMain')}>
        <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='请输入内容，不超过30个字' maxLength={30} showCount />
          </Form.Item>

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

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

          <div className='A1fromRow'>
            <Form.Item label='链接' name='url'>
              <Input placeholder='请输入' />
            </Form.Item>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='A1abtn'>
            <div className='A1abtnBox'>
              <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 MemoA1add = React.memo(A1add)

export default MemoA1add
