import { Button, Drawer, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react'
import { Document, Page } from 'react-pdf';
import Viewer from 'viewerjs';
import { isImg } from '../../renderers/Lion/utils/utils';
import { Shell } from '../../utils/shell';
import { tools } from '../../utils/shell/tools';
import { Icon } from '../icons';
import PopUp from '../PopUp';
import 'viewerjs/dist/viewer.css';
interface MoveUploadProps {
  props: any;
  maxTagCount: number;
  minTagCount: number;
  files: any[];
  file: any;
  errImg: string;
  index: number;
  onClick: () => void;
  readonly?: boolean;
  isImage?: boolean;
  dropzone?: React.RefObject<any>
}
interface MoveUploadimgProps {
  props: any;
  files: any[];
  file: any;
  errImg: string;
  index: number;
  formatFileSize: (string: number) => string;
  readonly?: boolean
  disabled?: boolean
  isImage?: boolean
  removeFile: () => void
  downloadFile: (url: string, name: string) => void
}
interface position {
  x: number;
  y: number
}

const hasShell = (env: any, file: any, files?: any, index?: number) => {
  const baseUrl = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi || "";
  if (tools.isAndroid) {
    if (files) {
      Shell.previewFile({ urls: files.map((val: any) => { return val.preview }) })
    } else {
      const fileName = file.name
      if (isImg(fileName)) {
        Shell.previewFile({ urls: [file.preview], current: index })
      } else
        Shell.previewPdf({ url: file.preview, name: fileName })
    }
  } else {
    if (files) {
      const urls = files.map((attachment: any) => {
        const url = new URL(encodeURI(attachment.preview))
        const search = url.search == '' ? `?fileName=${attachment.preview_name}` : `${url.search}&fileName=${attachment.preview_name}`
        url.search = search
        return url.href
      })
      Shell.previewFile({ urls, current: index })
    } else {
      const url = new URL(encodeURI(file.preview))
      const search = url.search == '' ? `?fileName=${file.preview_name}` : `${url.search}&fileName=${file.preview_name}`
      url.search = search
      Shell.previewFile({ urls: [url.href], current: index })
    }
  }
}

const MoveUpload: React.FC<MoveUploadProps> = ({ props, maxTagCount, files, minTagCount, file, errImg, index, onClick, readonly, isImage, dropzone }): JSX.Element => {

  const handleImgDom = async (index: number, url: string, dropzone: React.RefObject<any>) => {
    const container = dropzone.current
    const viewer = new Viewer(container, {
      url,
      navbar: true,
      toolbar: false,
      initialViewIndex: index,
      inline: false,
      zIndex: 9999,
      button: true,
      zoomable: true,
      title: true,
      tooltip: true,
      minZoomRatio: 0.1,
      maxZoomRatio: 100,
      movable: true,
      interval: 2000,
      hide: (env) => {
        viewer.destroy()
      }
    })
    return viewer
  }
  const { classnames: cx, env } = props

  const length = files.length - maxTagCount > 99 ? 99 : files.length - maxTagCount;
  if (maxTagCount !== undefined && maxTagCount <= index && maxTagCount > 1) {
    return <div className={cx('ImageControl-img-wrapper ddd')} style={{ display: 'none' }}>
      <img src={(file.thumbnailAddr || file.preview) || errImg} alt="" data-original1={file.preview || errImg} />
    </div>
  }

  return (
    <div className={cx('ImageControl-img-wrapper')} onClick={async (e) => {
      if (readonly && !(length > 0 && minTagCount == maxTagCount && maxTagCount == index + 1)) {
        e.stopPropagation();
        e.preventDefault()
        if ((isImage || !files.some(item => !isImg(item.name.toLowerCase())))) {
          if (Shell.hasShell()) {
            hasShell(env, file, files, index)
          } else if (dropzone !== undefined) {
            if (env.previewImagesMb) {
              const urls = files.map((val: any) => { return val.preview })
              env.previewImagesMb(urls, index)
            } else {
              const viewer = await handleImgDom(index, 'data-original1', dropzone)
              viewer.show()
            }
          }
          return
        }
      }
      onClick()
    }} >
      {length > 0 && minTagCount == maxTagCount && maxTagCount == index + 1 && <div className={cx('ImageControl-img-overlay')}>
        <span>
          +{length}
        </span>
      </div>}
      <img src={(file.thumbnailAddr || file.preview) || errImg} alt="" data-original1={file.preview || errImg} />
    </div>
  )
}

const MoveUploadimg: React.FC<MoveUploadimgProps> = ({ props, files, file, errImg, index, readonly, disabled, isImage, formatFileSize, removeFile, downloadFile }): JSX.Element => {
  const { classnames: cx, popOverContainer, multiple, env } = props
  const baseURL = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi || '';
  const [isOpened, setIsOpened] = useState<boolean>(false)
  // 第几个图片
  const [isOpenedIndex, setIsOpenedIndex] = useState<number>(0)
  // 确认删除
  const [open, setOpen] = useState<boolean>(false)
  // pdf有几页
  const [numPages, setNumPages] = useState<number>(0);
  // 查看pdf
  const [showPdf, setShowPdf] = useState(false);
  // pdfdom
  const pdfContainerRef = useRef(null)
  // pdf的宽度
  const [pdfWidth, setPdfWidth] = useState<number>(0);
  // 加载几页
  const [loadedPages, setLoadedPages] = useState<number>(5); // 初始加载5页
  // 是否可加载
  const [loadedDisabled, setLoadedDisabled] = useState<boolean>(false);
  const featLength = files.filter(item => isImg(item.name))
  useEffect(() => {
    if (!pdfContainerRef.current) return
    const pdfBody = pdfContainerRef.current as HTMLLIElement
    const pdfContainerWidth = pdfBody.clientWidth;
    setPdfWidth(pdfContainerWidth - 50)
  }, [pdfContainerRef.current]);

  const getOrigin = (first: position, second: position) => {
    return {
      x: (first.x + second.x) / 2,
      y: (first.y + second.y) / 2
    };
  }

  const getCanvasOffset = (first: position, second: position, initial: position) => {
    return {
      x: (first.x - second.x + initial.x),
      y: (first.y - second.y + initial.y)
    };
  }

  const getDistance = (start: position, stop: position) => {
    return Math.sqrt(Math.pow((stop.x - start.x), 2) + Math.pow((stop.y - start.y), 2));
  }

  useEffect(() => {
    if (!pdfContainerRef.current) return
    const pdfContent = pdfContainerRef.current as HTMLLIElement
    const pdfbody = pdfContent?.childNodes?.[0] as HTMLLIElement
    if (!pdfbody) return
    // const mc = new Hammer(pdfContent);
    let clientWidth = pdfbody.clientWidth;
    let clientHeight = pdfbody.clientHeight;
    let initialScale = 1;
    let distance: any = {}
    // 单只拖动
    let initialCanvasOffset = { x: 0, y: 0 };
    let lastTapTime = 0;
    let Offset = { x: 0, y: 0 };
    // 现在的位置
    let canvasOff = { x: 0, y: 0 }
    let origin = { x: 0, y: 0 }

    pdfbody.addEventListener('touchstart', (e: any) => {
      e.stopPropagation();
      if (e.touches.length === 1) {
        const currentTime = new Date().getTime();
        const tapDelay = currentTime - lastTapTime;
        lastTapTime = currentTime;
        if (tapDelay < 300) {
          if (initialScale > 1.5) {
            pdfbody.style.position = 'relative';
            pdfbody.style.top = canvasOff.y + 'px';
            pdfbody.style.left = canvasOff.x + 'px';
            pdfbody.style.transform = `scale(${1})`
            initialScale = 1
          } else {
            pdfbody.style.position = 'relative';
            pdfbody.style.top = canvasOff.y + 'px';
            pdfbody.style.left = canvasOff.x + 'px';
            pdfbody.style.transform = `scale(${2})`
            initialScale = 2
          }
          return
        }
        initialCanvasOffset = {
          x: e.touches[0].clientX,
          y: e.touches[0].clientY
        }
      } else if (e.touches.length > 1) {
        distance.start = getDistance({
          x: e.touches[0].screenX,
          y: e.touches[0].screenY
        }, {
          x: e.touches[1].screenX,
          y: e.touches[1].screenY
        });
        initialCanvasOffset = getOrigin({
          x: e.touches[0].screenX,
          y: e.touches[0].screenY
        }, {
          x: e.touches[1].screenX,
          y: e.touches[1].screenY
        })
      }
    });

    pdfbody.addEventListener('touchmove', (e: any) => {
      e.stopPropagation();

      if (e.touches.length === 2) {
        origin = getOrigin({
          x: e.touches[0].pageX,
          y: e.touches[0].pageY
        }, {
          x: e.touches[1].pageX,
          y: e.touches[1].pageY
        });
        distance.stop = getDistance({
          x: e.touches[0].screenX,
          y: e.touches[0].screenY
        }, {
          x: e.touches[1].screenX,
          y: e.touches[1].screenY
        });
        canvasOff = getCanvasOffset(
          origin,
          initialCanvasOffset,
          Offset
        )
        initialScale = distance.stop / distance.start;

        if (canvasOff.x < (-clientWidth - 100)) {
          canvasOff.x = -clientWidth - 100
        } else if (canvasOff.x > (clientWidth - 100)) {
          canvasOff.x = clientWidth - 100
        }
        if (canvasOff.y < (-clientHeight - 100)) {
          canvasOff.y = (-clientHeight - 100)
        } else if (canvasOff.y > (clientHeight - 100)) {
          canvasOff.y = clientHeight - 100
        }
        pdfbody.style.position = 'relative';
        pdfbody.style.top = canvasOff.y + 'px';
        pdfbody.style.left = canvasOff.x + 'px';
        pdfbody.style.transform = `scale(${initialScale})`
      } else if (e.touches.length === 1) {
        canvasOff = getCanvasOffset(
          {
            x: e.touches[0].clientX,
            y: e.touches[0].clientY
          },
          initialCanvasOffset,
          Offset
        )
        pdfbody.style.position = 'relative';
        if (canvasOff.x < 0 && canvasOff.x <= (-clientWidth + 100)) {
          canvasOff.x = (-clientWidth + 100)
        } else if (canvasOff.x > 0 && canvasOff.x >= (clientWidth - 100)) {
          canvasOff.x = clientWidth - 100
        }
        // if (canvasOff.y > 0) {
        //   canvasOff.y = 0
        // } else if (canvasOff.y < 0 && canvasOff.y <= (clientHeight + 100)) {
        //   canvasOff.y = clientHeight - 100
        // }
        pdfbody.style.top = canvasOff.y + 'px';
        pdfbody.style.left = canvasOff.x + 'px';
        pdfbody.style.transform = `scale(${initialScale})`
      }
    });

    pdfbody.addEventListener('touchend', (e: any) => {
      e.stopPropagation();
      Offset = canvasOff
    });

    return () => {
      pdfbody.removeEventListener('touchstart', () => { });
      pdfbody.removeEventListener('touchmove', () => { });
      pdfbody.removeEventListener('touchend', () => { });
    }

  }, [pdfContainerRef.current]);

  const handleShowPdf = () => {
    setShowPdf(true);
  }

  const onDocumentLoadSuccess = ({ numPages }: any) => {
    setNumPages(numPages);
    if (numPages < 5) {
      setLoadedPages(numPages);
      setLoadedDisabled(true)
    }
  }
  useEffect(() => {
    // 在组件挂载时加载首次5页
    loadMorePages();
  }, []); // 空数组表示只在组件挂载时运行

  const loadMorePages = () => {
    if (loadedPages < numPages) {
      // 如果还有更多页面要加载，加载5页或剩余不足5页的页面
      const newLoadedPages = Math.min(loadedPages + 5, numPages);
      setLoadedPages(newLoadedPages);
      if (newLoadedPages == numPages) {
        setLoadedDisabled(true)
      }
    }
  };

  const handleClosePdf = () => {
    setShowPdf(false);
  }

  const handleImgDom = async (index: number) => {
    const container = document.getElementById('containerss') as HTMLElement;
    const viewer = new Viewer(container, {
      url: "data-original",
      navbar: true,
      toolbar: false,
      initialViewIndex: index,
      inline: false,
      zIndex: 9999,
      button: true,
      zoomable: true,
      title: true,
      tooltip: true,
      minZoomRatio: 0.1,
      maxZoomRatio: 100,
      movable: true,
      interval: 2000,
      hide: (env) => {
        viewer.destroy()
      },
      view: (env) => {
        setIsOpenedIndex(isOpenedIndex)
      }
    })
    return viewer
  }

  const onClickShell = async () => {

    if (readonly) {
      if (Shell.hasShell()) {
        if (isImage || !files.some(item => !isImg(item.name.toLowerCase()))) {
          hasShell(env, file, files, index)
        } else {
          hasShell(env, file)
        }
        return
      } else {
        if (!isImg(file.name)) {
          if (env.previewPdfMb) {
            env.previewPdfMb(file.name, file.preview)
          } else
            handleShowPdf()
          return
        } else if (isImg(file.name) && env.previewImagesMb) {
          let urls = [file.preview]
          let idx = 0

          if (!files.some(item => !isImg(item.name.toLowerCase()))) {
            urls = files.map((val: any) => { return val.preview })
            idx = index
          }
          env.previewImagesMb(urls, idx)
          return
        }
        const viewer = await handleImgDom(featLength?.findIndex(item => item.preview == file.preview))
        viewer.show(true)
      }
      return
    }
    setIsOpened(true)
    setIsOpenedIndex(featLength?.findIndex(item => item.preview == file.preview))
  }
  return (
    <>
      <li className={cx('ImageControl-upload-li', !isImg(file.name) && 'ImageControl-upload-li-pdf')} key={index} onClick={onClickShell}>
        <img src={(file.thumbnailAddr || file.preview) || errImg} alt="" />
        {isImg(file.name) && <div style={{ display: 'none' }}>
          <img src={(file.thumbnailAddr || file.preview) || errImg} alt="" data-original={file.preview || errImg} />
        </div>}
        {!isImg(file.name) && <span className={'upload-li-pdf-name'}>{file.name}</span>}
      </li>
      <Drawer
        visible={showPdf}
        placement="right"
        height={"100%"}
        className={`process_drawer`}
        closable={false}
        width={'100%'}
        destroyOnClose
        zIndex={3000}
        getContainer={env.getModalContainer}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button type="primary" style={{ borderRadius: 5, margin: '0 4px' }} onClick={handleClosePdf}>关闭预览</Button>
            <Button type="primary" style={{ borderRadius: 5 }} onClick={loadMorePages} disabled={loadedDisabled}>
              加载更多{`(${loadedPages + "/" + numPages})`}
            </Button>
          </div>
        }
        bodyStyle={{ padding: 0 }}
      >
        <div className={`flow-drawer-header ImageControl-flow-drawer-header`}>
          <div className='left-text' onClick={handleClosePdf}>
            <Icon icon="title-left" style={{ width: '16px', height: '16px' }} />
          </div>
          <div className="flow-drawer-header-title">
            <div className="flow-drawer-title">{file.name}</div>
          </div>
          <div className="flow-drawer-extra" style={{ width: 36 }}>
            <span className="right-text">
            </span>
          </div>
        </div>
        <div ref={pdfContainerRef} className={'ImageControl-body'}>
          <Document
            className={'ImageControl-Document'}
            file={file.preview}
            onLoadSuccess={onDocumentLoadSuccess}
            error={() => { setLoadedDisabled(true); setLoadedPages(0); return <> 加载预览文件失败</> }}
            loading='加载中，请稍候...'
          >
            {Array.from({ length: loadedPages }).map((_, index) => (
              <Page
                className='mb24'
                key={index}
                pageNumber={index + 1}
                scale={1}
                width={pdfWidth}
                onRenderError={() => {
                  setLoadedDisabled(true);
                  setLoadedPages(0);
                }}
              />
            ))}
          </Document>
        </div>
      </Drawer>
      <PopUp
        isShow={isOpened}
        container={popOverContainer ?? env?.getModalContainer ?? document.getElementById('amis-modal-container')!}
        className={'popOverClassName ImgButton'}
        onHide={() => setIsOpened(false)}
        header={<div className={cx('TransferDropDown-header')}>
          <div className={cx('PopUp-content-title')}>
            <span className={cx('PopUp-content-name')}>{file.name}</span>
            <span className={cx('PopUp-content-size')}>{"(" + formatFileSize(file.size) + ")"}</span>
          </div>
        </div>}
        footer={
          <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => { setIsOpened(false) }} >
              取消
            </Button>
          </div>
        }
        multiple={multiple}
        showClose
        popOverHeatClassName={'PopUp-popOverHeat'}
      >
        <div className={cx('PopUp-content-BT')}>
          {!readonly && !disabled && <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => { setOpen(true) }} danger >
              删除
            </Button>
          </div>}
          <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={async () => {
              if (Shell.hasShell()) {
                if ((isImage || !files.some(item => !isImg(item.name.toLowerCase())))) {
                  hasShell(env, file, files, index)
                } else {
                  hasShell(env, file)
                }
                setIsOpened(false)
                return
              }
              if (!isImg(file.name)) {
                if (env.previewPdfMb) {
                  env.previewPdfMb(file.name, file.preview)
                } else
                  handleShowPdf()
                return
              } else if (isImg(file.name) && env.previewImagesMb) {
                const urls = [file.preview]
                env.previewImagesMb(urls)
                setIsOpened(false)
                return
              }

              const viewer = await handleImgDom(isOpenedIndex)
              setIsOpened(false)
              viewer.show(true)
            }} >
              预览
            </Button>
          </div>
          {!readonly && !disabled && <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => { downloadFile(file.downloadSrc, file.name) }} >
              下载
            </Button>
          </div>}
          {/* {!readonly && !disabled && <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => { }} >
              重命名
            </Button>
          </div>} */}
        </div>
      </PopUp>
      <PopUp
        isShow={open}
        className={'popOverClassName ImgButtonremove'}
        onHide={() => setOpen(false)}
        footer={
          <div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => { setOpen(false) }} >
              取消
            </Button>
          </div>
        }
        multiple
        container={popOverContainer ?? env?.getModalContainer ?? document.getElementById('amis-modal-container')!}
        popOverHeatClassName={'PopUp-popOverHeat'}
      >
        <div className={cx('PopUp-content-BT')}>
          {<div className={cx('PopUp-content-Button')}>
            <Button type="text" onClick={() => {
              removeFile();
              setOpen(false);
              setIsOpened(false);
            }} danger >
              确认删除
            </Button>
          </div>}
        </div>
      </PopUp>
    </>
  )
}



export {
  MoveUpload,
  MoveUploadimg
}