import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Checkbox, DatePicker, Input, Popconfirm, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import Y33setType, { infoType } from '@/pages/Y_goodsDetails/Y2look/Y33setType'
import { C2baseFormData, C2InputKeyArr } from './data'
import { C2InputKeyType } from './type'
import dayjs from 'dayjs'
import MyTable from '@/components/MyTable'
import ImageLazy from '@/components/ImageLazy'
import YtableVideo from '@/components/YtableVideo'
import { C2tableC } from '@/utils/tableData'
import { GoodFileType } from '@/pages/B_enterTibet/B3goodsTable/B3GaddNew/type'
import { selectObj } from '@/utils/select'
import { fileImgArr, fileVideoArr } from '@/store/action/layout'
import { API_C2dels, API_C2downS, C2_APIgetList } from '@/store/action/C2files'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { downFileFu, resJiLianFu } from '@/utils/history'
import { MessageFu } from '@/utils/message'
const { RangePicker } = DatePicker

function C2files() {
  // 是否是藏品查询
  const [mediaSearch, setmediaSearch] = useState(window.location.href.includes('mediaSearch'))

  useEffect(() => {
    if (1 + 1 !== 2) console.log(setmediaSearch)
  }, [])

  const dispatch = useDispatch()

  const [formData, setFormData] = useState(C2baseFormData)
  const formDataRef = useRef(C2baseFormData)

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  const [btnAc, setBtnAc] = useState('')

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 时间选择器改变
  const timeChange = useCallback(
    (date: any, dateString: any) => {
      let startTime = ''
      let endTime = ''
      if (dateString[0] && dateString[1]) {
        startTime = dateString[0] + ' 00:00:00'
        endTime = dateString[1] + ' 23:59:59'
      }
      setFormData({ ...formData, startTime, endTime })
    },
    [formData]
  )

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    dispatch(C2_APIgetList({ ...formDataRef.current, type: btnAc }))
    setCheckArr([])
  }, [btnAc, dispatch])

  useEffect(() => {
    getListFu()
  }, [getListFu, timeKey])

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: C2InputKeyType) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData(C2baseFormData)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  // 多选
  const [checkArr, setCheckArr] = useState<number[]>([])

  const checkFu = useCallback(
    (id: number) => {
      if (checkArr.includes(id)) setCheckArr(checkArr.filter(v => v !== id))
      else setCheckArr([...checkArr, id])
    },
    [checkArr]
  )

  // 批量和单个设置
  const [typeMo, setTypeMo] = useState({} as infoType)

  const tableInfo = useSelector((state: RootState) => state.C2files.tableInfo)

  const startBtn = useMemo(() => {
    let arr: any = [
      {
        title: '选择',
        width: 50,
        render: (item: GoodFileType) => (
          <Checkbox checked={checkArr.includes(item.id)} onChange={() => checkFu(item.id)} />
        )
      },
      {
        width: 100,
        title: '缩略图/视频',
        render: (item: GoodFileType) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]

          return fileImgArr.includes(fileNameLast) ? (
            <div className='tableImgAuto'>
              <ImageLazy width={60} height={60} srcBig={item.filePath} src={item.thumb} />
            </div>
          ) : fileVideoArr.includes(fileNameLast) ? (
            <YtableVideo src={item.filePath} />
          ) : (
            ' - '
          )
        }
      },
      {
        title: '附件类型',
        render: (item: GoodFileType) =>
          selectObj['附件类型'].find(v => v.value === item.type)?.label
      },
      {
        title: '附件用途',
        render: (item: GoodFileType) => (item.effect ? resJiLianFu(item.effect) : '（空）')
      }
    ]

    return arr
  }, [checkArr, checkFu])

  // 点击删除
  const delFu = useCallback(
    async (data: number[]) => {
      const res = await API_C2dels(data)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

  // 获取下载权限
  const downImg = useSelector((state: RootState) => state.A0Layout.downImg)

  // 点击批量下载
  const downsFu = useCallback(
    async (type: 1 | 2) => {
      const res = await API_C2downS(checkArr, type)
      if (res.code === 0) {
        MessageFu.success('下载成功')
        downFileFu(res.data, () => {
          setCheckArr([])
        })
      }
    },
    [checkArr]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: GoodFileType) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]
          return (
            <>
              {downImg['图片'] === '原图和缩略图' && fileImgArr.includes(fileNameLast) ? (
                <Popconfirm
                  title='请选择图片规格'
                  onConfirm={() => downFileFu(item.filePath)}
                  onCancel={() => downFileFu(item.thumb)}
                  okText='原图'
                  cancelText='缩略图'
                >
                  <Button size='small' type='text'>
                    下载
                  </Button>
                </Popconfirm>
              ) : (
                <Button
                  size='small'
                  type='text'
                  onClick={() => downFileFu(item.thumb || item.filePath)}
                >
                  下载
                </Button>
              )}

              <>
                <Button
                  hidden={mediaSearch}
                  size='small'
                  type='text'
                  onClick={() =>
                    setTypeMo({
                      ids: [item.id],
                      type: item.type,
                      effect: item.effect,
                      flag: '单个'
                    })
                  }
                >
                  设置
                </Button>
                {mediaSearch ? null : (
                  <MyPopconfirm txtK='删除' onConfirm={() => delFu([item.id])} />
                )}
              </>
            </>
          )
        }
      }
    ]
  }, [delFu, downImg, mediaSearch])

  return (
    <div className={styles.C2files}>
      <div className='pageTitle'>{mediaSearch ? '多媒体信息' : '藏品附件'}</div>

      {/* 第一行 */}
      <div className='C2top'>
        <div className='C2topll'>
          {[{ label: '全部', value: '' }, ...selectObj['附件类型']].map(v => (
            <Button
              key={v.value}
              onClick={() => setBtnAc(v.value)}
              type={btnAc === v.value ? 'primary' : 'default'}
            >
              {v.label}
            </Button>
          ))}
        </div>

        <div className='C2toprr'>
          {downImg['图片'] === '原图和缩略图' ? (
            <Popconfirm
              title='请选择图片规格'
              onConfirm={() => downsFu(1)}
              onCancel={() => downsFu(2)}
              okText='原图'
              cancelText='缩略图'
            >
              <Button type='primary' disabled={checkArr.length === 0}>
                批量下载
              </Button>
            </Popconfirm>
          ) : (
            <Button type='primary' disabled={checkArr.length === 0} onClick={() => downsFu(2)}>
              批量下载
            </Button>
          )}
          {mediaSearch ? null : (
            <>
              &emsp;
              <Button
                type='primary'
                disabled={checkArr.length === 0}
                onClick={() =>
                  setTypeMo({
                    ids: checkArr,
                    type: '',
                    effect: '',
                    flag: '多个'
                  })
                }
              >
                批量设置
              </Button>
            </>
          )}
          &emsp;
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;
          <Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      {/* 第二行 */}
      <div className='C2top C2top2'>
        <div className='C2topll'>
          {C2InputKeyArr.map(item => (
            <div key={item.name}>
              <span>{item.name}：</span>

              {item.type === '下拉框' ? (
                <Select
                  allowClear={true}
                  placeholder='全部'
                  value={formData[item.key]}
                  onChange={e => txtChangeFu(e, item.key)}
                  options={item.data}
                />
              ) : null}
              {item.type === '输入框' ? (
                <Input
                  placeholder='请输入'
                  maxLength={30}
                  value={formData[item.key]}
                  onChange={e => txtChangeFu(e.target.value, item.key)}
                />
              ) : null}

              {item.type === '级联' ? (
                <Cascader
                  // changeOnSelect
                  options={item.data}
                  value={formData.effect ? formData.effect.split(',') : null}
                  onChange={e => txtChangeFu(e ? e.join(',') : '', item.key)}
                  placeholder='全部'
                  fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                  allowClear={true}
                />
              ) : null}
            </div>
          ))}
          <div>
            <span>上传起止日期：</span>
            <RangePicker
              value={
                formData.startTime ? [dayjs(formData.startTime), dayjs(formData.endTime)] : null
              }
              onChange={timeChange}
            />
          </div>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={600}
        list={tableInfo.list}
        columnsTemp={C2tableC}
        lastBtn={tableLastBtn}
        startBtn={startBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />

      {typeMo.flag ? (
        <Y33setType succFu={getListFu} info={typeMo} closeFu={() => setTypeMo({} as infoType)} />
      ) : null}
    </div>
  )
}

const MemoC2files = React.memo(C2files)

export default MemoC2files
