import React, { useState, useMemo, useEffect } from 'react';
import { useDispatch, useSelector } from "react-redux";
import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload, Spin, message, Image } from 'antd';
import moment from 'moment';
import request from "superagent";

const Images = ['png', 'jpg', 'svg', 'jpeg']

export default function upload (props) {
   const { value = null, onChange = () => { }, maxCount, maxSize = 3, types = [], disabled = false, xunruanDecode, ...uploadOption } = props;
   const { FS_QINIU_DOMAIN, FS_QINIU_ACTION, FS_QINIU_ASSETS_DIR } = window.env;
   /**
    * fileList: [] # 参考
    * types: ['jpg'] # 限定文件类型
    * maxSize: 1024 # 限定文件大小 M
    */
   const [messageApi, contextHolder] = message.useMessage();
   const actions = useSelector(state => state.global.actions);
   const qiniuToken = useSelector(state => state.qiniuToken);
   const dispatch = useDispatch();
   //
   const [fileList_, setFileList_] = useState([]);
   const [previewImg, setPreviewImg] = useState(null);

   useEffect(() => {
      if (!qiniuToken?.data) {
         dispatch(actions.qiniuToken())
      }
   }, [])

   const uploadProps = {
      name: "file",
      action: FS_QINIU_ACTION,
      fileList: (value || fileList_).map((df, index) => {
         return {
            ...df,
            uid: df.uid || -index,
            status: df.status || 'done',
            name: df?.url?.split('/').pop() ?? df.name,
            url: df.url ?
               df.url.startsWith('http') ? df.url
                  : `${FS_QINIU_DOMAIN}/${df?.url}`
               : df.thumbUrl,
         }
      }),
      // disabled: disabled || (maxCount && fileList_.length >= maxCount),
      data: (file) => {
         return {
            token: qiniuToken.data,
            /** key 表现为文件名 */
            key: `${FS_QINIU_ASSETS_DIR}/${moment().format('YYYYMMDDHHmmss')}/${file.name}`,
         }
      },
      beforeUpload: (file) => {
         return new Promise((resolve, reject) => {
            if (maxCount && (value || fileList_).length >= maxCount) {
               messageApi.warning(`最多选择${maxCount}个文件上传`)
               return Upload.LIST_IGNORE
            }
            if (file.name.length > 60) {
               messageApi.warning(`文件名过长(大于60字符)，请修改后上传`);
               return Upload.LIST_IGNORE
            }
            if (file.size > maxSize * 1024 * 1024) {
               messageApi.warning(`文件须小于 ${maxSize} M`);
               return Upload.LIST_IGNORE
            }
            let fileNameArr = file.name.split('.')
            let postfix = ''
            if (fileNameArr.length > 1) {
               postfix = fileNameArr[fileNameArr.length - 1]
               postfix.toLowerCase()
            }
            if (types.length && (!types.includes(postfix) || !postfix)) {
               messageApi.warning(`请上传 ${types.join('，')} 类型的文件`);
               return Upload.LIST_IGNORE
            }
            return resolve()
         })
      },
      customRequest: xunruanDecode ? async (p) => {
         const { file, filename, onSuccess, onError } = p
         try {
            // 讯软解密
            const formData = new FormData();
            formData.append("file", file);
            const decodeRes = await request.post("/xunruan/decryption",).send(formData);
            onSuccess({
               ...decodeRes.text
            })
         } catch (error) {
            console.error(error);
            onError({})
         }
      } : undefined,


      onChange: (files) => {
         let fileList = files?.fileList?.map(f => {
            return {
               ...f,
               url: f.response?.key ?? f?.url ?? f.thumbUrl
            }
         })
         setFileList_(fileList);
         onChange(fileList)
      },
      onPreview: (file) => {
         const url = file?.url || `${FS_QINIU_DOMAIN} / ${file?.response.key}`
         let postfix = url.split('.').pop();
         postfix = postfix.toLowerCase();
         if (url.indexOf("pdf") !== -1 || url.indexOf("csv") !== -1) {
            window.open(url)
         } else if (Images.includes(postfix)) {
            setPreviewImg(url);
         } else {
            window.open(`https://view.officeapps.live.com/op/view.aspx?src=${url}`)
         }
      },
      // maxCount: maxCount,
      ...uploadOption
   }

   return (
      <Spin spinning={qiniuToken?.loading} >
         {contextHolder}
         <Upload Upload
            {...uploadProps}
         >
            {props.children || <Button icon={<UploadOutlined />} />}
         </Upload >
         {
            previewImg ? <Image
               style={{ display: 'none', }
               }
               src=""
               preview={{
                  visible: true,
                  src: previewImg,
                  onVisibleChange: (value) => {
                     setPreviewImg(null);
                  },
               }
               }
            /> : ''
         }
      </Spin >
   )
}
