/*
 * Creater:     柿子
 * CreateDate:  2022/12/28
 * Describe：   在线预览
 * */
import React, { Component } from 'react';
import { message, Modal } from 'antd';
import { Util } from 'tools';
import { httpConfig } from 'containers/config/httpConfig'
import FileViewer from 'react-file-viewer';

class FileOnlinePreview extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadUrl: '',
      fileLocalUrl: null,
      fileType: '',
      type: '',
      fileName: '',
    }
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    let httpUrl = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? httpConfig.ipDeault : windowHost;
    let uploadUrl = httpUrl + '/images/optomefile/';
    this.setState({ uploadUrl });
  }

  // 修改弹窗状态
  modifyVisible = (visible, fileData, type) => {
    visible && this.getFileData(fileData, type);
    this.setState({ visible, type }, () => {
      if (!this.state.visible) {
        const { fileLocalUrl } = this.state;
        window.URL = window.URL || window.webkitURL;
        fileLocalUrl && window.URL.revokeObjectURL(fileLocalUrl); // 清理内存
      }
    });
  }

  // 获取文件信息
  getFileData = (file, type) => {
    const { uploadUrl } = this.state;
    if (type === 'file') {
      let fileData = file && 'file' in file ? file.file?.originFileObj || {} : file?.originFileObj || file;
      let fileName = fileData?.name || '';
      window.URL = window.URL || window.webkitURL;
      this.setState({
        fileLocalUrl: window.URL.createObjectURL(fileData),
        fileType: fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length),
        fileName,
      })
    } else if (type === 'onlineImg') { // 已上传的线上图片
      console.log('file', file)
      let filePath = file?.filePath || '';
      let fileName = file?.name || filePath;
      this.setState({ fileLocalUrl: uploadUrl + filePath, fileType: filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length), fileName });
    } else {
      let fileName = file?.name || type;
      this.setState({
        fileLocalUrl: uploadUrl + type,
        fileType: fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length),
        fileName
      })
    }
  }

  // 预览错误
  handleError = Util.debounce((e) => {
    message.error('预览错误，请下载到本地查看')
  })

  // 下载
  handleFileDownload = () => {
    const { type, uploadUrl, fileLocalUrl, fileName } = this.state;
    if (type === 'file') {
      message.info('暂不支持下载');
      return
    };
    let filePath = type === 'onlineImg' ? fileLocalUrl : (uploadUrl + type);
    let fileSuffixName = filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length);
    if (fileSuffixName === 'jpg' || fileSuffixName === 'png' || fileSuffixName === 'jpeg' || fileSuffixName === 'gif') {
      type && (window.open((type === 'onlineImg' ? fileLocalUrl : (uploadUrl + type))));
    } else {
      let link = document.createElement('a');
      link.href = filePath;
      link.download = fileName || 'default';
      document.body.appendChild(link); // 添加到DOM中
      link.click();
      window.URL.revokeObjectURL(link.href); // 如果使用Blob URL或者Object URL, 使用完记得释放
      // 延时移除元素以确保下载能够开始
      setTimeout(function () {
        document.body.removeChild(link);
      }, 1000);
    }
  }

  render() {
    const { fileLocalUrl, fileType, visible } = this.state;
    return (
      <Modal
        visible={visible}
        okText="下载"
        width="800px"
        title={<div className="flex">在线预览<span style={{ fontSize: '13px', fontWeight: 'normal', color: '#f26f6f' }}>【如预览异常，可点击下载按钮下载到本地查看】</span></div>}
        onOk={this.handleFileDownload}
        onCancel={() => this.modifyVisible(false)}
      >
        <div style={{ height: '60vh', overflow: 'auto' }}>
          {
            visible && fileLocalUrl && (
              <FileViewer
                fileType={fileType}
                errorComponent={<div>预览错误，请下载到本地查看</div>}
                filePath={fileLocalUrl}
                onError={(e) => this.handleError(e)}
              />
            )
          }
        </div>
      </Modal>
    )
  }
};

export default FileOnlinePreview;