import React, { useCallback, useMemo, useState } from 'react'
import { Upload, Button, UploadProps, Select } from 'antd'
import { InboxOutlined } from '@ant-design/icons'
import { MessageFu } from '@/utils/message'
import styles from './index.module.scss'
import { B1Xtype } from '@/pages/B_enterTibet/B1collect/data'
import { baseURL, envFlag } from '@/utils/http'
import { fileTypeRes } from '@/store/action/layout'
import { getTokenFu } from '@/utils/storage'
import { API_C2dels } from '@/store/action/C2files'
import MyPopconfirm from '../MyPopconfirm'
import { DeleteOutlined } from '@ant-design/icons'
import { loginOutFu } from '../DingLogin/data'

const { Dragger } = Upload

type Props = {
  tableList: B1Xtype[]
  moduleId: number
  isShow: boolean
  closeFu: () => void
  succFu: (obj: any) => void
}

function ZupFile({ tableList, moduleId, isShow, closeFu, succFu }: Props) {
  // 附件列表
  const [fileList, setFileList] = useState<any[]>([])

  // const timeRef = useRef(-1)

  const FileProps: UploadProps = {
    name: 'file',
    // 支持上传文件夹
    directory: true,
    multiple: true,
    action: `${baseURL}${envFlag ? '' : '/api/'}cms/orderCollect/upload`,
    headers: {
      token: getTokenFu()
    },
    // 上传的额外参数
    data: file => ({
      dirCode: 'collectUpFiles',
      isDb: 'true',
      type: fileTypeRes(file.name),
      moduleId,
      isCompress: 'true'
    }),
    fileList,
    onChange(info: any) {
      setFileList([...info.fileList])

      const { status } = info.file

      // 检查请求状态
      const response = info.file.response || {}

      if (status !== 'uploading') {
        if (response.code !== 0) {
          setFileList(info.fileList.filter((v: any) => v.uid !== info.file.uid))
          MessageFu.error(`${info.file.name} 上传失败；${response.msg}`)
        }
        if (response.code === 5001 || response.code === 5002) {
          MessageFu.warning('登录失效!')
          loginOutFu()
          return false
        }

        // console.log(info.file, info.fileList);
      }
      if (status === 'done' && response.code === 0) {
        // console.log("-----", info);
        setFileList(
          info.fileList.map((v: any) => ({
            ...v,
            mySelect:
              info.file.uid === v.uid
                ? {
                    id: info.file.response.data.id,
                    goodsId: undefined,
                    name: info.file.name
                  }
                : v.mySelect
          }))
        )
      } else if (status === 'error') {
        MessageFu.error(`${info.file.name} 上传失败.`)
        // 去掉列表中的失败状态文件
        setFileList(info.fileList.filter((v: any) => v.uid !== info.file.uid))
      }
    },
    // 自定义列表
    itemRender: (originNode, file: any) => {
      const obj = file.mySelect || { goodsId: undefined }

      return (
        <span className='custom-upload-item'>
          {originNode}

          {file.status === 'done' ? (
            <>
              <span className='mySelect'>
                <Select
                  getPopupContainer={() => document.querySelector('#A1OMain')!}
                  style={{ width: 200 }}
                  placeholder='请选择'
                  value={obj.goodsId}
                  onChange={e => selectChangeFu(e, file.uid, file.mySelect.id)}
                  options={tableList.map(v => ({
                    value: v.id,
                    label: v.name
                  }))}
                />
                <span hidden={obj.goodsId}>请选择藏品</span>
              </span>
              <MyPopconfirm
                txtK='删除'
                onConfirm={async () => {
                  if (file.percent === 100) {
                    // console.log("-----还没有发请求删除", file);
                    const id = file.response.data.id
                    // 已经上传完成，发请求删除
                    const res = await API_C2dels([id])

                    if (res.code === 0) {
                      MessageFu.success('删除成功!')
                      setFileList(fileList.filter((v: any) => v.uid !== file.uid))
                    }
                  } else {
                    MessageFu.success('删除成功!')
                    setFileList(fileList.filter((v: any) => v.uid !== file.uid))
                  }
                }}
                Dom={
                  <div className='mySelectIcon'>
                    <DeleteOutlined />
                  </div>
                }
              />
            </>
          ) : null}
        </span>
      )
    }
  }

  // 下拉框改变
  const selectChangeFu = useCallback(
    (val: number, uid: string, id: number) => {
      setFileList(
        fileList.map(v => ({
          ...v,
          mySelect:
            v.uid === uid
              ? {
                  ...v.mySelect,
                  goodsId: v.mySelect.id === id ? val : v.mySelect.goodsId
                }
              : v.mySelect
        }))
      )
    },
    [fileList]
  )

  // 需要提交的数据
  const arrRes = useMemo(() => {
    return fileList.map((v: any) => v.mySelect || { goodsId: undefined })
  }, [fileList])

  // 点击提交
  const btnOk = useCallback(async () => {
    const obj: any = {}
    arrRes.forEach(v => {
      if (obj[v.goodsId]) obj[v.goodsId].push(v.id)
      else obj[v.goodsId] = [v.id]
    })

    succFu(obj)
    setFileList([])
    closeFu()
  }, [arrRes, closeFu, succFu])

  return (
    <div className={styles.ZupFile} hidden={!isShow}>
      <div className='ZupFileBox' id='A1OMain'>
        <div className='ZupFilell'>
          {/* 文件夹上传区域（支持拖拽） */}
          <Dragger {...FileProps}>
            <p className='ant-upload-drag-icon'>
              <InboxOutlined />
            </p>
            <p className='ant-upload-text'>点击或拖拽文件夹到此区域上传</p>
            <p className='ant-upload-hint'>支持上传整个文件夹及子目录文件</p>
          </Dragger>
        </div>
      </div>

      {/* 关闭按钮 */}
      <div className='ZupFileBtnX'>
        <Button
          type='primary'
          onClick={btnOk}
          disabled={fileList.length === 0 || arrRes.some(v => !v.goodsId)}
        >
          提交
        </Button>
        &emsp;
        <Button onClick={closeFu}>关闭</Button>
        {fileList.length ? (
          <>
            &emsp;
            <MyPopconfirm
              txtK='清空'
              onConfirm={() => setFileList([])}
              Dom={<Button danger>清空数据</Button>}
            />
          </>
        ) : null}
      </div>
    </div>
  )
}

export default ZupFile
