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

const { RangePicker } = DatePicker

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

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

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

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

  // PC海报图的ref
  const ZupPcImgRef = useRef<any>(null)

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

  // 展品的ref
  const ZupFilesRef1 = useRef<any>(null)

  // 展馆的ref
  const ZupFilesRef2 = useRef<any>(null)

  // 标题的音频
  const [nameAudio, setNameAudio] = useState({
    fileName: '',
    filePath: ''
  })

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

      setDirCode(data.dirCode)

      // 展示展品
      ZupFilesRef1.current?.setFileComFileFu({
        type: 'img',
        fileList: data.exhibitsFile || []
      })

      // 展示展馆
      ZupFilesRef2.current?.setFileComFileFu({
        type: 'img',
        fileList: data.exhibitionFile || []
      })

      // 设置 临时展览 / 常设展览
      setTimeType(data.type)

      // 设置 常设展览描述
      setTimeVal(data.typeRemark)

      // 设置 临时展览 时间
      if (data.dateStart && data.dateEnd) {
        setTimeArr([dayjs(data.dateStart), dayjs(data.dateEnd)])
      }

      // 设置地址
      setAddrType({
        key: data.addrType,
        txt: data.address
      })

      // 设置标题的 音频
      if (data.fileName && data.filePath) {
        setNameAudio({
          fileName: data.fileName,
          filePath: data.filePath
        })
      }
      // 设置富文本
      ZRichTextRef.current?.ritxtShowFu(JSON.parse(data.rtf))

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

      FormBoxRef.current?.setFieldsValue(obj)

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

      // 设置Pc海报
      ZupPcImgRef.current?.setFileComFileFu({
        fileName: '',
        filePath: data.thumbPc
      })
    }
  }, [])

  // 临时展览 常设展览的切换
  const [timeType, setTimeType] = useState('long')
  const [timeVal, setTimeVal] = useState('')
  // 格式为dayjs的格式，需要转换
  const [timeArr, setTimeArr] = useState<any>(null)

  // 地址
  const [addrType, setAddrType] = useState({
    key: 'inland',
    txt: ''
  })

  const addrTypeChangeFu = useCallback(
    (key: 'key' | 'txt', val: string) => {
      setAddrType({ ...addrType, [key]: val })
    },
    [addrType]
  )

  // 附件 是否 已经点击过确定
  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')

      // 临时展览的时候要判断
      if (timeType === 'temp') {
        if (!timeArr || !timeArr[0]) return MessageFu.warning('请选择临时展览时间!')
      }
      // 地址校验
      if (!addrType.txt) return MessageFu.warning('请输入地址!')

      let dateStart = ''
      let dateEnd = ''
      if (timeArr && timeArr[0] && timeArr[1]) {
        dateStart = dayjs(timeArr[0]).format('YYYY-MM-DD')
        dateEnd = dayjs(timeArr[1]).format('YYYY-MM-DD')
      }

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

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

      // 展品的校验
      const { sonFileIds: exhibitsFileIds } = ZupFilesRef1.current?.fileComFileResFu()

      if (exhibitsFileIds.length <= 0) {
        return MessageFu.warning('请最少上传一个展品!')
      }

      // 展馆的校验
      const { sonFileIds: exhibitionFileIds } = ZupFilesRef2.current?.fileComFileResFu()

      if (exhibitionFileIds.length <= 0) {
        return MessageFu.warning('请最少上传一个展馆!')
      }

      // pc海报
      const coverUrl2 = ZupPcImgRef.current?.fileComFileResFu()

      // 富文本标题集合
      let rtfNameArr: string[] = []
      if (rtf.val && rtf.val.txtArr && rtf.val.txtArr.length) {
        rtfNameArr = rtf.val.txtArr.map((v: any) => v.name)
      }

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        datePublish,
        thumb: coverUrl1.filePath,
        thumbPc: coverUrl2.filePath,
        rtf: JSON.stringify(rtf.val || ''),
        fileName: nameAudio.fileName,
        filePath: nameAudio.filePath,
        type: timeType,
        dateStart,
        dateEnd,
        addrType: addrType.key,
        address: addrType.txt,
        exhibitsFileIds: exhibitsFileIds.join(','),
        exhibitionFileIds: exhibitionFileIds.join(','),
        dirCode,
        typeRemark: timeVal,
        rtfTitle: JSON.stringify(rtfNameArr)
      }

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

      const res = await A2_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(`${editInfo.txt}成功!`)
        editInfo.id > 0 ? editTableFu() : addTableFu()
        closeFu()
      }
    },
    [
      timeVal,
      dirCode,
      addTableFu,
      addrType.key,
      addrType.txt,
      closeFu,
      editInfo.id,
      editInfo.txt,
      editTableFu,
      nameAudio.fileName,
      nameAudio.filePath,
      timeArr,
      timeType
    ]
  )

  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.A2add}>
      <div className={classNames('A2eMain', editInfo.txt === '查看' ? 'A2eMainLook' : '')}>
        <Form
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          scrollToFirstError
        >
          <div className='A2fromRow'>
            <Form.Item
              label='标题'
              name='name'
              rules={[{ required: true, message: '请输入标题!' }]}
              // getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
            >
              <TextArea
                readOnly={editInfo.txt === '查看'}
                style={{ width: '500px' }}
                maxLength={100}
                showCount
                placeholder='请输入内容'
              />
            </Form.Item>
            {/* 标题的无障碍音频 */}
            <div className='A2_1Frow'>
              <ZupAudio
                fileInfo={nameAudio}
                upDataFu={info => setNameAudio(info)}
                delFu={() => setNameAudio({ fileName: '', filePath: '' })}
                dirCode={dirCode}
                myUrl='cms/exhibition/upload'
                isLook={editInfo.txt === '查看'}
              />
            </div>
          </div>

          {/* 封面 */}
          <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/exhibition/upload'
                format={['image/jpeg', 'image/png']}
                formatTxt='png、jpg和jpeg'
                checkTxt='请上传封面图!'
                upTxt='最多1张'
                myType='thumb'
              />
            </div>
          </div>

          {/* PC海报 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span> </span>
              PC海报：
            </div>
            <div className='formRight'>
              <ZupOne
                ref={ZupPcImgRef}
                isLook={editInfo.txt === '查看'}
                fileCheck={false}
                size={5}
                dirCode={dirCode}
                myUrl='cms/exhibition/upload'
                format={['image/jpeg', 'image/png']}
                formatTxt='png、jpg和jpeg'
                checkTxt='请上传封面图!'
                upTxt='最多1张'
                myType='thumb'
              />
            </div>
          </div>

          {editInfo.txt === '查看' ? <br /> : null}

          <Form.Item label='摘要' name='digest'>
            <TextArea
              readOnly={editInfo.txt === '查看'}
              placeholder='请输入内容'
              maxLength={1000}
              showCount
            />
          </Form.Item>

          {/* 时间 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              时间：
            </div>
            <div className='formRight'>
              <div>
                <Select
                  value={timeType}
                  onChange={e => setTimeType(e)}
                  style={{ width: 150 }}
                  options={[
                    { value: 'long', label: '常设展览' },
                    { value: 'temp', label: '临时展览' }
                  ]}
                />
                &emsp;
                {timeType === 'long' ? (
                  <Input
                    style={{ width: 536 }}
                    maxLength={100}
                    showCount
                    value={timeVal}
                    onChange={e => setTimeVal(e.target.value)}
                    placeholder='在此填入时间备注（选填），如9:00 - 17:00 (closed on Mondays)'
                  />
                ) : (
                  <RangePicker
                    value={timeArr && timeArr[0] ? timeArr : null}
                    onChange={val => setTimeArr(val)}
                  />
                )}
              </div>
              <div
                className={classNames(
                  'formRight5Tit',
                  fileCheck && timeType === 'temp' && (!timeArr || !timeArr[0])
                    ? 'formRight5TitErr'
                    : ''
                )}
              >
                请选择时间!
              </div>
            </div>
          </div>

          {/* 地址 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              地址：
            </div>
            <div className='formRight'>
              <div>
                {[
                  { name: '国内', key: 'inland' },
                  { name: '国外', key: 'foreign' }
                ].map(item => (
                  <Radio
                    key={item.name}
                    checked={addrType.key === item.key}
                    onClick={() => addrTypeChangeFu('key', item.key)}
                  >
                    {item.name}
                  </Radio>
                ))}
                &emsp;
                <Input
                  readOnly={editInfo.txt === '查看'}
                  style={{ width: 536, marginLeft: 14 }}
                  maxLength={100}
                  showCount
                  value={addrType.txt}
                  onChange={e => addrTypeChangeFu('txt', e.target.value)}
                  placeholder='请输入内容'
                />
              </div>
              <div
                className={classNames(
                  'formRight5Tit',
                  fileCheck && !addrType.txt ? 'formRight5TitErr' : ''
                )}
              >
                请输入地址!
              </div>
            </div>
          </div>

          {/* 概况 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              概况：
            </div>
            <div className='formRight'>
              <ZRichTexts
                check={fileCheck}
                dirCode={dirCode}
                isLook={editInfo.txt === '查看'}
                ref={ZRichTextRef}
                myUrl='cms/exhibition/upload'
              />
            </div>
          </div>

          {/* 展品 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              展品：
            </div>
            <div className='formRight'>
              <ZupTypes
                ref={ZupFilesRef1}
                selecFlag='图片'
                fileCheck={fileCheck}
                dirCode={dirCode}
                myUrl='cms/exhibition/upload'
                isLook={editInfo.txt === '查看'}
                imgLength={30}
                isTypeShow={true}
                isUpName={true}
              />
            </div>
          </div>

          {/* 展馆 */}
          <div className='formRow'>
            <div className='formLeft'>
              <span>* </span>
              展馆：
            </div>
            <div className='formRight'>
              <ZupTypes
                ref={ZupFilesRef2}
                selecFlag='图片'
                fileCheck={fileCheck}
                dirCode={dirCode}
                myUrl='cms/exhibition/upload'
                isLook={editInfo.txt === '查看'}
                imgLength={30}
                isTypeShow={true}
              />
            </div>
          </div>

          <Form.Item
            label='发布日期'
            name='myTime'
            rules={[{ required: true, message: '请选择发布日期!' }]}
          >
            <DatePicker />
          </Form.Item>

          <div className='A2fromRow'>
            <Form.Item
              label='排序值'
              name='sort'
              rules={[{ required: true, message: '请输入排序值!' }]}
            >
              <InputNumber min={1} max={999} precision={0} placeholder='请输入' />
            </Form.Item>
            <div className='A2_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='A2Ebtn'>
            {editInfo.txt === '查看' ? (
              <Button onClick={closeFu}>返回</Button>
            ) : (
              <>
                <Button type='primary' htmlType='submit'>
                  提交
                </Button>
                <br />
                <br />
                <MyPopconfirm txtK='取消' onConfirm={closeFu} />
              </>
            )}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

const MemoA2add = React.memo(A2add)

export default MemoA2add
