import React from 'react';
import Base64 from 'base64-js';
import styled from 'styled-components';
import { Icon, message } from 'antd';
import { config, networkUtils } from '../../utils';

const { api } = config;
const { fm } = api;

const Tools = styled.div`
  text-align: center;
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  font-size: 2rem;
  font-weight: bold;

  i:hover{
    cursor: pointer;
    font-size: 2rem;
    color: #FFCC33;
  }
`;

const Item = styled.div`
  min-width: 250px;
  width: 250px;
  height: 200px;
  margin-right: 10px;
  position: relative;

  &:hover img, &:hover video {
    opacity: 0.3;
    transition: .5s ease;
    backface-visibility: hidden;
  }

  &:hover ${Tools} {
    opacity: 1;
  }
`;

const renderEntity = (src, fileName) => {
  if (src.match(/.(jpg|jpeg|png|gif)$/i)) {
    return (<img style={{ height: '100%', width: '100%' }} src={src}/>);
  } else if (src.match(/.(mp4|webm|Ogg|3gp|flv)$/i)) {
    return (
      <video style={{ height: '100%', width: '100%' }}>
        <source src={src}/>
      </video>
    );
  } else {
    // return (<h5>该文件类型不支持预览</h5>);
    // return <Icon type="file" />;
    return fileName;
  }
};

const downloader = (data, fileName) => {
  const a = document.createElement('a');
  // a.style = 'display: none';
  a.style.display = 'none';

  document.body.appendChild(a);

  const blob = new Blob([Base64.toByteArray(data)]);
  if ('msSaveOrOpenBlob' in window.navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  }
};

const handleClickPreview = (src) => {
  const win = window.open(src, '_blank');
  win.focus();
};

const handleClickDownload = (fileName, repo) => {
  // console.log(fileName);
  networkUtils.request({
    url: fm.download.replace('{repo}', repo).replace('{file}', fileName),
    method: 'get',
  }).then((data) => {
    if (data.success) {
      message.success('下载成功!');
      // this.fetchData()
      downloader(data.data, fileName);
    } else {
      throw data;;
    }
  });
};

const Entity = ({ file, repo }) => {
  const pictures = file.fileName.match(/.(jpg|jpeg|png|gif|mp4|webm|Ogg|3gp|flv)$/i);
  return (
    <Item style={{ border: `1px solid ${pictures ? 'transparent' : 'lightgray' }` }}>
      {renderEntity(`/repos/${repo}/${file.fileName}`, file.fileName)}
      <Tools>
        {pictures && <Icon
        type="eye-o"
        style={{ marginRight: 20 }}
        onClick={handleClickPreview.bind(this, `/repos/${repo}/${file.fileName}`)}
      />}
      <Icon
        type="download"
        onClick={handleClickDownload.bind(this, file.fileName, repo)}
      />
      </Tools>
    </Item>
  );
};

export default Entity;
