
import React from 'react';
import { RendererProps } from '../../../../../factory';
import { FormItem, FormControlProps, FormBaseControl } from '../../../../Form/Item'
import Upload, { UploadProps } from 'antd/lib/Upload';
import Button from 'antd/lib/Button';

import PdfFile from '../../../Table/LionCellFile/PdfPreview/index'
import '../../../font/iconfont.css';
import { Wrapper } from './style';
import { findDOMNode } from 'react-dom';
import LionFilePreview from '../../../Table/LionCellFile/LionFilePreview'

interface IState {
  fileList: any[];
  showfilelist: any;
  params: string;
  turtyfilelist: any[];
  current: any;
  visible: boolean;
}

export interface LionShowFileSchema extends FormBaseControl {
  type: 'lion-show-file';
}

export interface LionShowFileProps extends FormControlProps, Omit<LionShowFileSchema, 'type' | 'className' | 'descriptionClassName' | 'inputClassName'> { }

export class LionShowFile extends React.PureComponent<LionShowFileProps & UploadProps & RendererProps, IState>{

  state = {
    visible: false,
    current: null as any,
    fileList: [],
    showfilelist: [] as any,
    params: '',
    turtyfilelist: [] as any
  };

  componentDidMount() {
    this.props?.onChange && this.props?.onChange('');
    this.initFileData()
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    if (this.props !== prevProps) {
      this.initFileData()
    }
  }

  initFileData() {
    const { data, name, env, store } = this.props;
    const baseUrl = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi;
    let content = data[name as string] || store?.data[name as string];
    if (content) {
      const { info, value } = content;
      if (info && value && info.length !== 0) {
        let initialList: any = [];
        info.map((ele: any) => {
          initialList.push({
            uid: ele.name,
            status: 'done',
            name: ele.name,
            url: (baseUrl ? baseUrl : '') + (ele?.addr || ele?.url)
          })
        })
        this.setState({
          params: value,
          showfilelist: [
            ...initialList
          ],
          turtyfilelist: [
            ...initialList
          ]
        });
      }
    }
  }

  handleOpenPdf = (file: any) => {
    this.setState({
      current: file
    }, () => {
      this.setState({
        visible: true
      })
    });
  }

  matchLocalhost = (str: string) => {
    return /localhost\:(\d)+/.test(str)
  }

  openDownloadDialog = (url: any, saveName: string) => {
    return new Promise((resolve, reject) => {
      resolve('')
    }).then(res => {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) event = new MouseEvent('click');
      else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      }
      aLink.dispatchEvent(event);
    })
  }

  getThatDom(): any {
    return findDOMNode(this)
  }


  render() {
    const { showfilelist, visible, current } = this.state;
    const { env } = this.props;
    const baseUrl = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi;
    const that = this;

    const uploadButton = (
      <div style={{
        display: 'inline-block',
        textAlign: 'center',
        cursor: 'pointer',
        outline: 'none',
        marginTop: '12px',
        fontSize: '12px',
        color: '#444'
      }}>
        <Button
          size='middle'
          style={{
            width: '56px',
            height: '32px',
            border: '1px solid #ebeef5',
            borderRadius: '4px',
            fontWeight: 500,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            fontSize: '14px !important',
            padding: '9px 15px',
            cursor: 'not-allowed',
            color: "#c0c4cc",
            backgroundImage: 'none',
            backgroundColor: "#fff"
          }}
          disabled={true}
        >
          上传
        </Button>
      </div>
    );

    const uploadProps: UploadProps = {
      listType: "text",
      disabled: false,
      iconRender: () => <span className="fa fa-file-text-o"></span>,
      showUploadList: {
        showPreviewIcon: true,
        showRemoveIcon: true,
        showDownloadIcon: true,
        downloadIcon: <span style={{ fontSize: '12px' }} className="fa fa-cloud-download"></span>,
        removeIcon: <span style={{ color: 'rgb(24,144,255)', fontSize: '12px' }} className="fa fa-folder-open-o"></span>
      },
      onDownload: (file: any) => {
        // baseUrlAddr (!baseUrl ? '' : (this.matchLocalhost(baseUrl) ? '' : baseUrl))
        const downloadFileUlr = file?.url || file?.addr;
        this.openDownloadDialog(downloadFileUlr, file?.name)
      },
      onPreview: (file: any) => false,
      onRemove: (file: any) => {
        this.handleOpenPdf({
          ...file,
          url: file?.url?.replace(baseUrl, '')
        }); Promise.resolve().then(() => this.getThatDom()?.click()); return false
      },
      fileList: showfilelist
    };

    return (
      <>
        <Wrapper>
          <Upload style={{ width: '70px', fontSize: '12px' }} {...uploadProps}>
            {uploadButton}
          </Upload>
        </Wrapper>
        {/* <div style={{ display: 'flex', cursor: 'pointer', alignItems: 'center' }}>
          <Tooltip
            zIndex={9000}
            placement="bottom"
            overlayInnerStyle={{
              background: '#fff',
              width: '300px',
              zIndex: 9000
            }}

            title={
              showfilelist && showfilelist.length > 0 ? <div style={{ width: "278px", background: '#fff', color: '#333' }}>
                {
                  showfilelist.map((item: any, idx: number) => {
                    return <div className="fastlion-tooltip-bottom" key={item.name} style={{
                      lineHeight: '26px',
                      width: '278px',
                      padding: '5px 16px',
                      display: 'flex',
                      alignItems: 'center',
                      fontSize: '14px',
                      justifyContent: 'space-between',
                    }}>
                      <Tooltip
                        placement={idx === showfilelist.length - 1 ? 'bottom' : 'top'}
                        title={item.name}
                        zIndex={9999}
                        overlayInnerStyle={{
                          zIndex: 9999
                        }}
                        arrowPointAtCenter={true}
                      >
                        <span style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                        }}>
                          <LinkOutlined style={{
                            fontSize: '13px'
                          }} />
                          &nbsp;&nbsp;

                          <span style={{
                            width: '160px', whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}>

                            {item.name}
                          </span>
                        </span>
                      </Tooltip>
                      <Tooltip overlayInnerStyle={{ zIndex: 9999 }} zIndex={9999} placement='top' title='打开'>
                        <Button onClick={() => { this.handleOpenPdf(item) }} style={{ border: 0 }} icon={<FolderOpenOutlined style={{ fontSize: '13px' }} />}></Button>
                      </Tooltip>
                    </div>
                  })
                }
              </div> : null
            }
          >
            <Tooltip
              overlayInnerStyle={{
                background: '#303133',
                width: '278px',
                height: 'auto',
                padding: '5px 8px',
                zIndex: 9000
              }}
              title={
                showfilelist && showfilelist.length > 1 ? <div style={{ background: '#303133', display: 'flex', height: "auto", alignItems: 'center' }}
                >
                  <span style={{
                    color: '#fff'
                  }}>
                    <span style={{
                      color: "#999",
                      width: '50px'
                    }}>附件：</span>
                    {showfilelist ? <LinkOutlined style={{
                      fontSize: '12px'
                    }} /> : null}
                    {showfilelist ? showfilelist.length : null}
                                    &nbsp;&nbsp;
                  {
                      showfilelist && showfilelist.length > 0 ?
                        showfilelist[0].name : null
                    }
                  </span>

                </div>
                  : null
              }
              placement="top"
              mouseEnterDelay={0.5}
              zIndex={9000}
            >
              <span
                style={{
                  display: 'flex',
                  cursor: showfilelist ? 'pointer' : 'text',
                  alignItems: 'center'
                }}>
                <span style={{
                  display: 'flex',
                  alignItems: 'center'
                }}>
                  <LinkOutlined style={{
                    fontSize: '12px'
                  }} />
                  {showfilelist && showfilelist.length > 0 ? showfilelist.length : null}
                  &nbsp;&nbsp;
                  <span style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    width: '200px'
                  }}>
                    {
                      showfilelist && showfilelist.length > 0 ?
                        showfilelist.map((item: any, idx: any) => {
                          if (idx === showfilelist.length - 1) {
                            return item.name
                          }
                          return item.name + ' , '
                        }) : '暂无附件'
                    }
                  </span>
                  {showfilelist && showfilelist.length > 0 ? (showfilelist.length > 1 ? <DownOutlined style={{
                    marginLeft: '10px',
                    fontWeight: 400,
                    fontSize: '12px',
                    color: "#999"

                  }} /> : null) : null}
                </span>

              </span>
            </Tooltip>
          </Tooltip>
        </div> */}
        <LionFilePreview {...this.props} visible={visible} current={current} setVisible={() => {
          that.setState({
            visible: false
          })
        }} />
      </>
    );
  }
}

@FormItem({
  type: 'lion-show-file',
  strictMode: false
})
export class LionShowFileRenderer extends LionShowFile { }
