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 { A7_APIgetInfo, A7_APIadd, A7_APIedit } from '@/store/action/A7collection'
import { MessageFu } from '@/utils/message'
import ZupOne from '@/components/ZupOne'
import MyPopconfirm from '@/components/MyPopconfirm'
import dayjs from 'dayjs'
import { A7AddType, A7tableType } from '@/types/api/A7collection'
import ZupTypes from '@/components/ZupTypes'

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

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

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

  // 附件的ref
  const ZupTypesRef = useRef<any>(null)

  // 回显数据的方法调用
  const dataShow = useCallback((info: A7tableType) => {
    let editObj = null
    if (info.status === 0) {
      editObj = {
        ...info,
        title: info.titleB,
        type: info.typeB,
        era: info.eraB,
        texture: info.textureB,
        size: info.sizeB,
        publish: info.publishB,
        remark: info.remarkB,
        img: info.imgB,
        imgTh: info.imgThB,
        typeModel: info.typeModelB,
        typeImage: info.typeImageB,
        typeAudio: info.typeAudioB,
        typeVideo: info.typeVideoB,
        modelFile: info.modelFileB,
        imageFiles: info.imageFilesB,
        videoFile: info.videoFileB,
        audioFile: info.audioFileB,
        webSite: info.webSiteB,
        level: info.levelB
      }
    } else {
      editObj = { ...info }
    }
    FormBoxRef.current?.setFieldsValue({ ...editObj, publish: dayjs(editObj.publish) })

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

    // 设置附件
    const imgFileList = editObj.typeImage
      ? editObj.imageFiles.map((v: any) => ({
          fileName: v.split('/').pop(),
          filePath: v,
          id: v,
          type: 'img'
        }))
      : []
    ZupTypesRef.current?.setFileComFileFu({
      fileList: [
        ...imgFileList,
        editObj.typeModel && {
          fileName: editObj.modelFile,
          filePath: editObj.modelFile,
          id: editObj.modelFile,
          type: 'model'
        },
        editObj.typeAudio && {
          fileName: editObj.audioFile.split('/').pop(),
          filePath: editObj.audioFile,
          id: editObj.audioFile,
          type: 'audio'
        },
        editObj.typeVideo && {
          fileName: editObj.videoFile.split('/').pop(),
          filePath: editObj.videoFile,
          id: editObj.videoFile,
          type: 'video'
        }
      ],
      type: [
        editObj.typeImage && 'img',
        editObj.typeModel && 'model',
        editObj.typeAudio && 'audio',
        editObj.typeVideo && 'video'
      ]
    })
  }, [])

  // 编辑 进入页面 获取信息
  const getInfoFu = useCallback(
    async (id: number) => {
      if (editInfo.info) dataShow(editInfo.info)
      else {
        const res = await A7_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 { fileList, sonType, sonIsOk } = ZupTypesRef.current?.fileComFileResFu()
      // 没有传 封面图
      if (!coverUrl1.url) return MessageFu.warning('请上传首页封面图!')
      if (sonIsOk) return MessageFu.warning('请上传附件!')

      // 发布
      const obj1: A7AddType = {
        ...values,
        publish: values.publish?.format('YYYY-MM-DD') || '',
        img: coverUrl1.url,
        imgTh: coverUrl1.thUrl,
        status: 1,
        modelFile: fileList.model.filePath || '',
        imageFiles: fileList.img.map((v: any) => v.filePath) || [],
        videoFile: fileList.video.filePath || '',
        audioFile: fileList.audio.filePath || '',
        typeModel: sonType.includes('model') || false,
        typeImage: sonType.includes('img') || false,
        typeAudio: sonType.includes('audio') || false,
        typeVideo: sonType.includes('video') || false
      }

      // 预发布
      const obj2: A7AddType = {
        ...values,
        audioFileB: fileList.audio.filePath || '',
        eraB: values.era,
        imageFilesB: fileList.img.map((v: any) => v.filePath) || [],
        imgB: coverUrl1.url,
        imgThB: coverUrl1.thUrl,
        modelFileB: fileList.model.filePath || '',
        publishB: values.publish?.format('YYYY-MM-DD') || '',
        remarkB: values.remark,
        sizeB: values.size,
        status: 0,
        textureB: values.texture,
        titleB: values.title,
        typeAudioB: sonType.includes('audio') || false,
        typeB: values.type,
        typeImageB: sonType.includes('img') || false,
        typeModelB: sonType.includes('model') || false,
        typeVideoB: sonType.includes('video') || false,
        videoFileB: fileList.video.filePath || '',
        webSiteB: '',
        levelB: values.level
      }

      let res: any
      if (btnRef.current === '1') {
        res =
          editInfo.txt === '新增'
            ? await A7_APIadd(obj1)
            : await A7_APIedit({ ...obj1, artifactId: editInfo.id })
      } else {
        res =
          editInfo.txt === '新增'
            ? await A7_APIadd(obj2)
            : await A7_APIedit({ ...obj2, artifactId: 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.A7add}>
      <div className={classNames('A7aMain')}>
        <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='type' initialValue={4}>
            <Select
              defaultValue={0}
              placeholder='请选择类别'
              options={[
                { label: '棉麻丝绸', value: 1 },
                { label: '铁器、其他金属器', value: 2 },
                { label: '文物、宣传品', value: 3 },
                { label: '其他', value: 4 }
              ]}
            />
          </Form.Item>

          <Form.Item label='级别' name='level'>
            <Input placeholder='请输入内容，最多10字' maxLength={10} showCount />
          </Form.Item>

          <Form.Item label='年代' name='era'>
            <Input placeholder='请输入内容，最多10字' maxLength={10} showCount />
          </Form.Item>

          <Form.Item label='质地' name='texture'>
            <Input placeholder='请输入内容，最多10字' maxLength={10} showCount />
          </Form.Item>

          <Form.Item label='尺寸' name='size'>
            <Input placeholder='请输入内容，最多30字' maxLength={30} showCount />
          </Form.Item>

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

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

          <Form.Item
            label={
              <>
                <span style={{ color: 'red' }}>*</span> 文件类型
              </>
            }
            name='file'
          >
            <ZupTypes
              ref={ZupTypesRef}
              selecFlag='模型/图片/音频/视频'
              fileCheck={fileCheck}
              dirCode='A7collection'
              myUrl='museum/upload/upload'
              imgSize={20}
            />
          </Form.Item>

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

          {/* 确定和取消按钮 */}
          <Form.Item className='A7abtn'>
            <div className='A7abtnBox'>
              <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 MemoA7add = React.memo(A7add)

export default MemoA7add
