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,
  InputNumber,
  TimePicker
} from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { A5_APIgetInfo, A5_APIadd, A5_APIedit } from '@/store/action/A5activity'
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 { A5AddType, A5tableType } from '@/types/api/A5activity'

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

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

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

  // 回显数据的方法调用
  const dataShow = useCallback((info: A5tableType) => {
    let editObj = null
    if (info.status === 0) {
      editObj = {
        ...info,
        title: info.titleB,
        publish: info.publishB,
        remark: info.remarkB,
        context: info.contextB,
        indexImg: info.indexImgB,
        indexImgTh: info.indexImgThB,
        infoImg: info.infoImgB,
        infoImgTh: info.infoImgThB
      }
    } else {
      editObj = { ...info }
    }
    FormBoxRef.current?.setFieldsValue({
      ...editObj,
      publish: dayjs(editObj.publish),
      date: editObj.subscribe === 1 ? [dayjs(editObj.startTime), dayjs(editObj.endTime)] : [],
      time:
        editObj.subscribe === 1
          ? [dayjs(editObj.time.split('-')[0], 'HH:mm'), dayjs(editObj.time.split('-')[1], 'HH:mm')]
          : []
    })

    // 设置封面图
    ZupThumbRef1.current?.setFileComFileFu({
      fileName: '',
      thUrl: editObj.indexImgTh,
      url: editObj.indexImg
    })
    ZupThumbRef2.current?.setFileComFileFu({
      fileName: '',
      thUrl: editObj.infoImgTh,
      url: editObj.infoImg
    })

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

  // 编辑 进入页面 获取信息
  const getInfoFu = useCallback(
    async (id: number) => {
      if (editInfo.info) dataShow(editInfo.info)
      else {
        const res = await A5_APIgetInfo(id)
        if (res.code === 0) {
          dataShow(res.data)
          setIsReserve(res.data.subscribe || 0)
        }
      }
    },
    [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 coverUrl2 = ZupThumbRef2.current?.fileComFileResFu()
      const context = ZRichTextRef.current?.fatherBtnOkFu()
      // 没有传 封面图
      if (!coverUrl1.url) return MessageFu.warning('请上传首页封面图!')
      if (!coverUrl2.url) return MessageFu.warning('请上传详情封面图!')
      if (!context.val.txtArr[0].txt) return MessageFu.warning('请输入正文!')

      // 发布
      const obj1: A5AddType = {
        ...values,
        indexImg: coverUrl1.url,
        indexImgTh: coverUrl1.thUrl,
        infoImg: coverUrl2.url,
        infoImgTh: coverUrl2.thUrl,
        context: context.val.txtArr[0].txt,
        publish: values.publish?.format('YYYY-MM-DD') || '',
        publishB: '',
        status: 1,
        titleB: '',
        urlB: '',
        startTime: values?.date?.[0]?.format('YYYY-MM-DD') || '',
        endTime: values?.date?.[1]?.format('YYYY-MM-DD') || '',
        personCount: values?.personCount || 1,
        time: values?.time?.map((item: any) => item.format('HH:mm')).join('-') || '',
        guide: values?.guide || ''
      }

      // 预发布
      const obj2: A5AddType = {
        indexImg: '',
        indexImgB: coverUrl1.url,
        indexImgTh: '',
        indexImgThB: coverUrl1.thUrl,
        infoImg: '',
        infoImgB: coverUrl2.url,
        infoImgTh: '',
        infoImgThB: coverUrl2.thUrl,
        publish: '',
        publishB: values.publish?.format('YYYY-MM-DD') || '',
        status: 0,
        subscribe: values.subscribe,
        title: '',
        titleB: values.title,
        remark: '',
        remarkB: values.remark,
        context: '',
        contextB: context.val.txtArr[0].txt,
        startTime: values?.date?.[0]?.format('YYYY-MM-DD') || '',
        endTime: values?.date?.[1]?.format('YYYY-MM-DD') || '',
        personCount: values?.personCount || 1,
        time: values?.time?.map((item: any) => item.format('HH:mm')).join('-') || '',
        guide: values?.guide || ''
      }

      let res: any
      if (btnRef.current === '1') {
        res =
          editInfo.txt === '新增'
            ? await A5_APIadd(obj1)
            : await A5_APIedit({ ...obj1, activityId: editInfo.id })
      } else {
        res =
          editInfo.txt === '新增'
            ? await A5_APIadd(obj2)
            : await A5_APIedit({ ...obj2, activityId: 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('')

  const [isReserve, setIsReserve] = useState(0)

  return (
    <div className={styles.A5add}>
      <div className={classNames('A5aMain')}>
        <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='请输入内容，不超过50个字' maxLength={50} showCount />
          </Form.Item>

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

          <Form.Item label='摘要' name='remark'>
            <TextArea maxLength={200} showCount placeholder='请输入内容，不超过200个字' />
          </Form.Item>

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

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

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

          <Form.Item
            label='需要预约'
            name='subscribe'
            initialValue={0}
            rules={[{ required: true, message: '请选择预约类型！' }]}
          >
            <Select
              defaultValue={0}
              onChange={val => {
                setIsReserve(val)
              }}
              options={[
                { label: '是', value: 1 },
                { label: '否', value: 0 }
              ]}
            />
          </Form.Item>

          {isReserve === 1 && (
            <div className='reserveBox'>
              <Form.Item
                label='活动日期'
                name='date'
                rules={[{ required: !!isReserve, message: '请选择活动日期' }]}
              >
                <DatePicker.RangePicker />
              </Form.Item>
              <Form.Item
                label='可预约人数'
                name='personCount'
                initialValue={1}
                rules={[{ required: !!isReserve, message: '请输入可预约人数' }]}
              >
                <InputNumber defaultValue={1} min={1} max={9999} />
              </Form.Item>
              <Form.Item
                label='活动时间段'
                name='time'
                rules={[{ required: !!isReserve, message: '请选择活动时间段' }]}
              >
                <TimePicker.RangePicker
                  format='HH:mm'
                  disabledTime={() => ({
                    disabledHours: () => [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23],
                    disabledMinutes: currentHour => {
                      if (currentHour === 20) {
                        return Array.from({ length: 59 }, (_, i) => i + 1)
                      }
                      return []
                    }
                  })}
                />
              </Form.Item>
            </div>
          )}

          {/* 确定和取消按钮 */}
          <Form.Item className='A5abtn'>
            <div className='A5abtnBox'>
              <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 MemoA5add = React.memo(A5add)

export default MemoA5add
