import {
  Button,
  Cascader,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Radio,
  Select,
  Table
} from 'antd'
import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons'
import TextArea from 'antd/es/input/TextArea'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import classNames from 'classnames'
import './index.css'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import ImageLazy from '../ImageLazy'
import {
  delInfileAPI,
  getInfoInAPI,
  goodsSonAddAPI,
  object1AddUpFileAPI
} from '@/store/action/object1'
import { goodsChangeObj } from '@/utils/dataChange'
import { editObj2GoodsAPI } from '@/store/action/object2'
import { MessageFu } from '@/utils/message'
const { Option } = Select

type Props = {
  id: any
  colsePage: any
  editId?: any
  dirCode: any
  upInfoAPIFu?: any
}

function ObjectAdd({ id, colsePage, editId, dirCode, upInfoAPIFu }: Props) {
  const dispatch = useDispatch()

  // 没有通过校验
  const onFinishFailed = () => {
    setTitSelect('tit1')
    return MessageFu.warning('有表单不符号规则!')
  }

  // --------通过校验之后发送请求----------点击确定
  const onFinish = async (values: any) => {
    const oldObj = {} as any
    for (const k in values) {
      if (values[k]) oldObj[k] = values[k]
    }

    // 外形尺寸 3个 字段 变成一个组数
    const size = [values.size1, values.size2, values.size3]
    // 具体质量 + 单位
    let quality = [] as any
    if (values.quality) quality = [values.quality, danweiValue]
    // 文件id
    const fileIds = [] as any

    // 新的完整附件数据
    const newDataFile = [] as any

    for (const k in results) {
      results[k].forEach((v: any) => {
        fileIds.push(v.id)
        newDataFile.push(v)
      })
    }
    // 年代
    const dictAge = values.dictAge.join('/')
    // 文物质地
    const dictTexture = values.dictTexture.join('/')

    const obj = {
      ...oldObj,
      id: id ? id : null,
      size: size.join(','),
      quality: quality.join(','),
      thumb: cover,
      dirCode: dirCode + '',
      fileIds: fileIds.join(','),
      registerId: dirCode,
      dictAge,
      dictTexture,
      display: values.display
    }

    // -----------------藏品修改
    if (editId === 'edit') {
      // 表单信息对比
      const oldData = oldDataRef.current.entity

      // 有变化的数据---更新前
      const before = {} as any
      // 有变化的数据---更新后
      const after = {} as any

      for (const k in obj) {
        if (oldData[k] !== obj[k] && goodsChangeObj[k] && k !== 'fileIds') {
          before[k] = oldData[k]
          after[k] = obj[k]
        } else if (k === 'fileIds') {
          // 单独处理附件信息
          before['fileIds'] = oldDataRef.current.file.map((v: any) => v.id).join(',')
          after['fileIds'] = newDataFile.map((v: any) => v.id).join(',')

          before['fileIdsName'] = oldDataRef.current.file.map((v: any) => v.name).join(',')
          after['fileIdsName'] = newDataFile.map((v: any) => v.name).join(',')

          if (
            before['fileIds'] === after['fileIds'] ||
            before['fileIdsName'] === after['fileIdsName']
          ) {
            delete before['fileIds']
            delete after['fileIds']
            delete before['fileIdsName']
            delete after['fileIdsName']
          }
        }
      }
      if (JSON.stringify(before) === '{}') return MessageFu.warning('没有改变藏品的信息!')

      const editData = {
        afterJson: after,
        beforeJson: before,
        goodsIds: Number(id)
      }

      const res: any = await editObj2GoodsAPI(editData)
      if (res.code === 0) {
        MessageFu.success('编辑成功!')
        // 通知父组件更新页面
        upInfoAPIFu()
        // 真正的删除 ----在藏品总账里面修改的时候不能删除
        // if (delFileList.current.length) {
        //   await delInfileAPI(delFileList.current.join(","));
        // }
        //  关闭弹窗
        colsePage()
      }

      console.log('旧数据', before)
      console.log('新数据', after)
    } else {
      // ------------藏品新增和编辑
      await dispatch(goodsSonAddAPI(obj, id))

      // 真正的删除
      if (delFileList.current.length) {
        await delInfileAPI(delFileList.current.join(','))
      }
      //  关闭弹窗
      colsePage()
    }
  }

  // 选择商品信息还是附近（默认商品信息）
  const [titSelect, setTitSelect] = useState('tit1')

  // 从仓库中获取各下拉数据
  const options1 = useSelector((state: RootState) => state.loginStore.selectAll['藏品编号名称'])

  const options2 = useSelector((state: RootState) => state.loginStore.selectAll['年代'])
  const options3 = useSelector((state: RootState) => state.loginStore.selectAll['质地'])
  const options4 = useSelector((state: RootState) => state.loginStore.selectAll['文物类别'])
  const options5 = useSelector((state: RootState) => state.loginStore.selectAll['文物级别'])
  const options6 = useSelector((state: RootState) => state.loginStore.selectAll['质量范围'])
  const options7 = useSelector((state: RootState) => state.loginStore.selectAll['完残程度'])
  const options8 = useSelector((state: RootState) => state.loginStore.selectAll['保存状态'])
  const options9 = useSelector((state: RootState) => state.loginStore.selectAll['入藏时间范围'])

  // 单位选择
  const [danweiValue, setDanweiValue] = useState('kg')

  // 把旧的数据保存起来--用于藏品修改的对比
  const oldDataRef = useRef<any>({})

  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<any>({})
  const getInfoInAPIFu = useCallback(
    async (id: number) => {
      const res = await getInfoInAPI(id)

      // 把旧的数据存起来
      oldDataRef.current = res.data

      const data = res.data.entity
      const size = data.size.split(',')

      const quality = data.quality ? data.quality.split(',') : ['', 'kg']

      const dictAge = data.dictAge.split(',')
      const dictTexture = data.dictTexture.split(',')
      FormBoxRef.current.setFieldsValue({
        ...data,
        size1: size[0],
        size2: size[1],
        size3: size[2],
        quality: quality[0],
        dictAge,
        dictTexture
      })
      // 具体质量的单位
      setDanweiValue(quality[1])
      // 藏品图片
      setCover(data.thumb)

      const fileData = {
        img: [],
        video: [],
        audio: [],
        model: [],
        doc: []
      } as any
      res.data.file.forEach((v: any) => {
        fileData[v.type].push(v)
      })
      // 修改附件仓库信息
      dispatch({ type: 'login/setFileData', payload: fileData })
    },
    [dispatch]
  )

  // 进页面看看是编辑就 从仓库获取信息，新增就设置默认值
  useEffect(() => {
    if (id) {
      getInfoInAPIFu(id)
    } else {
      FormBoxRef.current.setFieldsValue({
        dictNum: options1[0].name ? options1[0].name : null,
        dictAge: ['地质年代', '显生宙', '新生代', '第四纪'],
        dictTexture: ['单一质地', '有机质', '竹'],
        dictGoodType: options4[0].name ? options4[0].name : null,
        dictLevel: options5[0].name ? options5[0].name : null,
        dictQualityScope: options6[0].name ? options6[0].name : null,
        complete: options7[0].name ? options7[0].name : null,
        dictCheckInScope: options9[0].name ? options9[0].name : null,
        display: 0
      })
      // 初始化附件仓库信息
      dispatch({
        type: 'login/setFileData',
        payload: {
          img: [],
          video: [],
          audio: [],
          model: [],
          doc: []
        }
      })
    }
  }, [dispatch, getInfoInAPIFu, id, options1, options4, options5, options6, options7, options9])

  // -----------关于藏品附件的信息
  const [fileSelect, setFileSelect] = useState('img')

  const fileSelectChangeFu = (value: string) => {
    setFileSelect(value)
  }

  const results = useSelector((state: RootState) => state.loginStore.fileData)

  // 点击表格里面的删除
  const delOne = useCallback(
    (id: number) => {
      const data = {
        ...results,
        [fileSelect]: results[fileSelect].filter((v: any) => v.id !== id)
      }
      dispatch({ type: 'login/setFileData', payload: data })

      // 把删除的id存起来
      delFileList.current.push(id)
    },
    [dispatch, fileSelect, results]
  )

  // 表格格式
  const columns = useMemo(() => {
    const tempArr = [
      {
        title: '附件名称',
        dataIndex: 'name'
      },
      {
        title: '上传时间',
        dataIndex: 'createTime'
      },
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button type='text' danger onClick={() => upFileFu(item.id)}>
              重传
            </Button>
            <Popconfirm
              title='确定删除吗?'
              okText='确定'
              cancelText='取消'
              onConfirm={() => delOne(item.id)}
            >
              <Button type='text' danger>
                删除
              </Button>
            </Popconfirm>
          </>
        )
      }
    ]

    if (fileSelect === 'img') {
      tempArr.unshift({
        title: '缩略图',
        render: (item: any) => (
          <div className='tableImg'>
            <ImageLazy width={120} height={70} src={item.filePath} />
          </div>
        )
      })
    }

    return tempArr
  }, [delOne, fileSelect])

  // 封面地址
  const [cover, setCover] = useState('')

  const fileSelectList = useMemo(() => {
    return [
      { id: 1, value: 'img', label: '高清图片' },
      { id: 2, value: 'video', label: '视频文件' },
      { id: 3, value: 'audio', label: '音频文件' },
      { id: 4, value: 'model', label: '三维模型' },
      { id: 5, value: 'doc', label: '文档资料' }
    ]
  }, [])

  // 上传附件的进度条
  const UpAsyncLodingDom: any = document.querySelector('#UpAsyncLoding')
  const progressDom: any = document.querySelector('#progress')

  // 上传封面
  const myInput = useRef<HTMLInputElement>(null)
  const handeUpPhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      // 拿到files信息
      const filesInfo = e.target.files[0]
      // 校验格式
      const type = ['image/jpeg', 'image/png']
      if (!type.includes(filesInfo.type)) {
        e.target.value = ''
        return MessageFu.warning('只支持jpg、png格式!')
      }
      // 校验大小
      if (filesInfo.size > 10 * 1024 * 1024) {
        e.target.value = ''
        return MessageFu.warning('最大支持10M!')
      }
      // 创建FormData对象
      const fd = new FormData()
      // 把files添加进FormData对象（‘photo’为后端需要的字段）
      fd.append('type', 'thumb')
      fd.append('dirCode', dirCode)
      fd.append('file', filesInfo)

      e.target.value = ''

      const res: any = await object1AddUpFileAPI(fd)
      if (res.code === 0) {
        MessageFu.success('上传成功!')
        setCover(res.data.filePath)
      }
      UpAsyncLodingDom.style.opacity = 0
      progressDom.style.width = '0%'
    }
  }

  // 上传附件
  const myInput2 = useRef<HTMLInputElement>(null)

  const upFileFlagRef = useRef(false)

  const delFileList = useRef<any>([])

  const upFileFu = (flag?: any) => {
    upFileFlagRef.current = flag ? flag : 0
    myInput2.current?.click()
  }
  const handeUpPhoto2 = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0]

        let type = [] as string[]

        let tit = ''

        if (fileSelect === 'img' || fileSelect === 'video' || fileSelect === 'audio') {
          if (fileSelect === 'img') {
            type = ['image/jpeg', 'image/png', 'image/gif']
            tit = '只支持jpg、png、gif格式!'
          } else if (fileSelect === 'video') {
            type = ['video/mp4']
            tit = '只支持mp4格式!'
          } else if (fileSelect === 'audio') {
            type = ['audio/mpeg']
            tit = '只支持mp3格式!'
          }
          // 校验格式
          if (!type.includes(filesInfo.type)) {
            e.target.value = ''
            return MessageFu.warning(tit)
          }
        }

        // 创建FormData对象
        const fd = new FormData()
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append('type', fileSelect)
        fd.append('dirCode', dirCode)
        fd.append('file', filesInfo)
        e.target.value = ''

        const res: any = await object1AddUpFileAPI(fd)
        if (res.code === 0) {
          MessageFu.success('上传成功!')
          if (upFileFlagRef.current) {
            // 重新上传
            const id = upFileFlagRef.current
            const data = {
              ...results,
              [fileSelect]: results[fileSelect].map((v: any) => {
                if (id !== v.id) return v
                else
                  return {
                    ...res.data
                  }
              })
            }
            dispatch({ type: 'login/setFileData', payload: data })

            // 把删除的id存起来
            delFileList.current.push(upFileFlagRef.current)
          } else {
            // 新上传
            const data = {
              ...results,
              [fileSelect]: [
                {
                  ...res.data
                },
                ...results[fileSelect]
              ]
            }

            dispatch({ type: 'login/setFileData', payload: data })
          }
        }
        UpAsyncLodingDom.style.opacity = 0
        progressDom.style.width = '0%'
      }
    },
    [UpAsyncLodingDom.style, dirCode, dispatch, fileSelect, progressDom.style, results]
  )

  return (
    <div className={styles.ObjectAdd}>
      <Modal
        wrapClassName='ObjectAdd'
        destroyOnClose
        open={true}
        title={id ? '编辑藏品' : '添加藏品'}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        {/* 商品信息和附件切换 */}
        <div className='ObjectAddTit'>
          <div
            onClick={() => setTitSelect('tit1')}
            className={classNames(titSelect === 'tit1' ? 'active' : '')}
          >
            藏品信息
          </div>
          <div
            onClick={() => setTitSelect('tit2')}
            className={classNames('ObjectAddTitTow', titSelect === 'tit2' ? 'active' : '')}
          >
            附件
          </div>
        </div>

        <Form
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          {/* -----------------------表单信息 */}
          <div className='formBox' hidden={titSelect === 'tit2'}>
            {/* 藏品名称----------原名 */}
            <div className='formRow'>
              <Form.Item
                label='藏品名称'
                name='name'
                rules={[{ required: true, message: '不能为空!' }]}
                getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
              >
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
              <Form.Item label='原名' name='namePrimitive'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
            </div>
            {/* 藏品编号名称----------藏品编号 */}
            <div className='formRow'>
              <div className='bs'>*</div>
              <Form.Item label='藏品编号名称' name='dictNum'>
                <Select
                  placeholder='请选择'
                  options={options1.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
              <Form.Item label='藏品编号' name='num'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
            </div>
            {/* 年代----------文物质地 */}
            <div className='formRow'>
              <div className='bs bs2'>*</div>
              <div className='bs bs3'>*</div>
              <Form.Item label='年代' name='dictAge'>
                <Cascader
                  allowClear={false}
                  fieldNames={{
                    label: 'name',
                    value: 'name',
                    children: 'children'
                  }}
                  options={options2}
                  placeholder='请选择'
                />
              </Form.Item>
              <Form.Item label='文物质地' name='dictTexture'>
                <Cascader
                  allowClear={false}
                  fieldNames={{
                    label: 'name',
                    value: 'name',
                    children: 'children'
                  }}
                  options={options3}
                  placeholder='请选择'
                />
              </Form.Item>
            </div>
            {/* 具体年代----------文物类别 */}
            <div className='formRow'>
              <div className='bs bs3'>*</div>
              <Form.Item label='具体年代' name='ageSpecific'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
              <Form.Item label='文物类别' name='dictGoodType'>
                <Select
                  placeholder='请选择'
                  options={options4.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
            </div>
            {/* 实际数量----------文物级别 */}
            <div className='formRow'>
              <div className='bs bs3'>*</div>
              <Form.Item
                rules={[{ required: true, message: '不能为空!' }]}
                label='实际数量'
                name='pcs'
              >
                <InputNumber min={1} maxLength={8} placeholder='请输入数字' />
              </Form.Item>
              <Form.Item label='文物级别' name='dictLevel'>
                <Select
                  placeholder='请选择'
                  options={options5.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
            </div>
            {/* 外形尺寸----------通长，宽，高 */}
            <div className='formRow formRowThree'>
              <Form.Item
                rules={[{ required: true, message: '不能为空!' }]}
                label='外形尺寸'
                name='size1'
              >
                <InputNumber min={1} maxLength={8} placeholder='通长' addonAfter='cm' />
              </Form.Item>
              <Form.Item rules={[{ required: true, message: '不能为空!' }]} label='' name='size2'>
                <InputNumber min={1} maxLength={8} placeholder='通宽' addonAfter='cm' />
              </Form.Item>
              <Form.Item
                className='formRowThreeRow'
                rules={[{ required: true, message: '不能为空!' }]}
                label=''
                name='size3'
              >
                <InputNumber min={1} maxLength={8} placeholder='通高' addonAfter='cm' />
              </Form.Item>
            </div>
            {/* 具体尺寸*/}
            <div className='formRow formRowFull'>
              <Form.Item
                label='具体尺寸'
                name='sizeSpecific'
                rules={[{ required: true, message: '不能为空!' }]}
                getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
              >
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
            </div>
            {/* 质量范围----------具体质量 */}
            <div className='formRow'>
              <div className='bs bs4'>*</div>
              <Form.Item label='质量范围' name='dictQualityScope'>
                <Select
                  placeholder='请选择'
                  options={options6.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
              <Form.Item className='formRowSelec' label='具体质量' name='quality'>
                <InputNumber
                  min={1}
                  maxLength={8}
                  placeholder='请输入数字'
                  addonAfter={
                    <Select value={danweiValue} onChange={val => setDanweiValue(val)}>
                      <Option value='kg'>kg</Option>
                      <Option value='g'>g</Option>
                    </Select>
                  }
                />
                {/* <div className="formRowSelecSon">

              </div> */}
              </Form.Item>
            </div>
            {/* 完残程度----------保存状态 */}
            <div className='formRow'>
              <div className='bs bs4'>*</div>
              <Form.Item label='完残程度' name='complete'>
                <Select
                  placeholder='请选择'
                  options={options7.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
              <Form.Item label='保存状态' name='repair'>
                <Select
                  placeholder='请选择'
                  options={options8.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
            </div>
            {/* 入藏时间范围----------入藏年度 */}
            <div className='formRow'>
              <div className='bs'>*</div>
              <Form.Item label='入藏时间范围' name='dictCheckInScope'>
                <Select
                  placeholder='请选择'
                  options={options9.map((v: any) => ({
                    label: v.name,
                    value: v.name
                  }))}
                />
              </Form.Item>
              <Form.Item label='入藏年度' name='checkInYear'>
                <InputNumber min={1000} maxLength={4} placeholder='请输入数字' />
              </Form.Item>
            </div>
            {/* 著者----------版本 */}
            <div className='formRow'>
              <Form.Item label='著者' name='author'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
              <Form.Item label='版本' name='vision'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
            </div>
            {/* 存卷*/}
            <div className='formRow formRowFull'>
              <Form.Item label='存卷' name='onFile'>
                <Input maxLength={50} showCount placeholder='请输入' />
              </Form.Item>
            </div>
            {/* 来源说明*/}
            <div className='formRow formRowFull'>
              <Form.Item label='来源说明' name='description'>
                <TextArea rows={3} placeholder='请输入' showCount maxLength={255} />
              </Form.Item>
            </div>

            {/* 备注 */}
            <div className='formRow formRowFull'>
              <Form.Item label='备注' name='remark'>
                <TextArea rows={3} placeholder='请输入' showCount maxLength={255} />
              </Form.Item>
            </div>

            <div className='formRow formRowLast'>
              <Form.Item
                rules={[{ required: true, message: '不能为空!' }]}
                label='展示状态'
                name='display'
              >
                <Radio.Group>
                  <Radio value={1}> 是 </Radio>
                  <Radio value={0}> 否 </Radio>
                </Radio.Group>
              </Form.Item>
            </div>
          </div>
          {/* -----------------------附件信息 */}
          <div hidden={titSelect === 'tit1'}>
            <div className='fileBox'>
              {/* 封面上传 */}
              <div className='fileBoxRow'>
                <div className='fileBoxRow_tit'>藏品图片：</div>
                <div className='fileBoxRow_r'>
                  <div
                    hidden={cover !== ''}
                    className='fileBoxRow_up'
                    onClick={() => myInput.current?.click()}
                  >
                    <PlusOutlined />
                    <input
                      type='file'
                      accept='.png,.jpg'
                      ref={myInput}
                      onChange={e => handeUpPhoto(e)}
                    />
                  </div>
                  <div className='fileBoxRow_r_img' hidden={cover === ''}>
                    {cover ? <ImageLazy width={120} height={120} src={cover} /> : null}

                    <Popconfirm
                      title='确定删除吗?'
                      okText='确定'
                      cancelText='取消'
                      onConfirm={() => setCover('')}
                    >
                      <div className='clearCover'>
                        <CloseCircleOutlined />
                      </div>
                    </Popconfirm>
                  </div>
                  <div className='fileBoxRow_r_tit'>支持上传jpg，png格式，大小&lt;10M</div>
                </div>
              </div>
              {/* 附件上传 */}
              <div className='fileBoxRow'>
                <div className='fileBoxRow_tit fileBoxRow_tit2'>上传附件：</div>
                <div className='fileBoxRow_r'>
                  <input type='file' ref={myInput2} onChange={e => handeUpPhoto2(e)} />
                  <Select
                    style={{ width: 150 }}
                    value={fileSelect}
                    onChange={fileSelectChangeFu}
                    options={fileSelectList}
                  />
                  &emsp;
                  <Button onClick={() => upFileFu()}>上传附件</Button>
                </div>
                &emsp;
                <div className='fileBoxRowUpTit'>
                  {fileSelect === 'img' ? (
                    <>支持上传jpg，png，gif格式</>
                  ) : fileSelect === 'video' ? (
                    <>支持上传mp4格式</>
                  ) : fileSelect === 'audio' ? (
                    <>支持上传mp3格式</>
                  ) : (
                    ''
                  )}
                </div>
              </div>
              {/* 表格主体 */}
              <div className='addTableBox_table'>
                <Table
                  size='small'
                  scroll={{ y: 300 }}
                  dataSource={results[fileSelect]}
                  columns={columns}
                  rowKey='id'
                  pagination={false}
                />
              </div>
            </div>
          </div>

          <br />
          <Form.Item wrapperCol={{ offset: 20 }}>
            <Button onClick={colsePage}>取消</Button>
            &emsp;
            <Button type='primary' htmlType='submit'>
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

const MemoObjectAdd = React.memo(ObjectAdd)

export default MemoObjectAdd
