/**
 * 钟是志
 * 2024年7月4日
 * 解决禅道 http://scjoyedu.eicp.net:57400/zentao/task-view-2695.html
 * 根据配置项来解决
 * word,excel等文件转换成pdf并预览
 * */
import React, { useMemo, Fragment, useState, useRef } from "react";
import { fileUrlToFilePath } from '@/webPublic/one_stop_public/utils/queryConfig';
import { requestOrigin } from '@/webPublic/one_stop_public/utils/request';
import { message, Popconfirm, Tooltip } from 'antd';
import { getPdfFile } from "@/webPublic/one_stop_public/filePreview/utils";
import { isFromIframe } from "@/webPublic/one_stop_public/utils/utils";

export default function PreviewWordExtend({ src, fileName }) {
	const extList = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt'];
	const [isShow, setIsShow] = useState(false);
	const filePdf = useRef(null);
	const isOpen = useMemo(
		() => {
			return window.CONFIG.openPdfPreview && extList.includes(fileName.split('.').pop());
		},
		[src],
	);
	function showPdf() {
	  if(!filePdf.current){
      const params = {
        filePath: fileUrlToFilePath(src),
      };
      message.info('正在打开文件预览,请耐心等待', 10);
      getPdfFile(params).then((url) => {
        filePdf.current = url;
        setIsShow(true);
      });
    }else{
	    setIsShow(true);
    }

	}

	function downloadFile() {
	  let a = document.createElement('a');
	  a.href = src;
	  a.target = '_blank';
	  a.download = fileName;
	  a.click();
	}


	if (isOpen) {
		return (
			<Fragment>
      <Popconfirm
          title="查看附件"
          onConfirm={downloadFile}
          okText="下载"
          onCancel={showPdf}
          cancelText={'预览'}
      >
				<a>{fileName}</a>
      </Popconfirm>
        {
          isShow &&
          <Modal title={'文件预览'}
                 width={1000}
                 visible={isShow}
                 onCancel={() => setIsShow(false)}
                 bodyStyle={{
                   height: '600px',
                   overflowY: 'hidden',
                 }}
                 footer={null}
          >
            <a target={'_blank'} href={src}>
              下载文件
            </a>
            <embed width="100%"
                   height='550'
                   name="plugin"
                   id="plugin"
                   src={filePdf.current}
                   type="application/pdf"
                   internalinstanceid="3"
                   title=""/>
          </Modal>
        }

			</Fragment>
		);
	} else {
		return (
      <>
        {
          fileName?.length > 13 ?
          <Tooltip title={fileName}>
            <a href={src} target={'_blank'}>
              {fileName.substring(0, 10)}...
            </a>
          </Tooltip>
           :
          <a href={src} target={'_blank'}>
            {fileName}
          </a>
        }
      </>

		);
	}
}
