import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Upload, Tabs } from 'amos-framework';
import Player from 'xgplayer';
import FlvPlayer from 'xgplayer-flv';
import { request, payload, api } from '@gm/graphmod-utils';
import ImageConst from '@gm/graphmod-assets';
import Tip from '../tip';
import './AssetsUpload.scss';

const { compleHeaders } = request;
const { UrlConsts } = api;

const { TabList, Tab, TabPanel } = Tabs;
const oneMb = 1024;
const assets = {
  'png': { type: 'image' },
  'jpg': { type: 'image' },
  'jpeg': { type: 'image' },
  'mp4': { type: 'video', image: ImageConst.common.vedioIcon },
  'flv': { type: 'video', image: ImageConst.common.vedioIcon },
  'pdf': { type: 'file', image: ImageConst.common.pdf },
  'docx': { type: 'file', image: ImageConst.common.word },
  'doc': { type: 'file', image: ImageConst.common.word }
};

/**
 * 公共资源上传
 *
 * @class AssetsUpload
 * @extends {Component}
 */
class AssetsUpload extends Component {

  static propTypes = {
    type: PropTypes.oneOf(['add', 'edit', 'look']), // 改组件是添加还是编辑还是删除页面的组件
    assetsTabs: PropTypes.array, // 上传tabs分类集合
    data: PropTypes.object, // 上传的文件数据
    onChange: PropTypes.func // 上传文件数据变化函数
  };

  static defaultProps = {
    type: 'add',
    assetsTabs: [],
    data: {},
    onChange() {
    }
  };

  constructor(props) {
    super(props);
    this.initShowMax = false; // 是否初始化预览第一个资源
    this.state = {
      // 默认资源类型Tab页
      activeKey: (props.assetsTabs || []).length > 1 ? 'all' : (props.assetsTabs[0] || {}).key,
      fileList: [],
      preview: {}
    };
  }

  componentDidMount() {
    this.initShowMax = this.getDefaultPreview();
  }

  componentWillReceiveProps(nextProps){

    this.setState({
      activeKey: (nextProps.assetsTabs || []).length > 1 ? 'all' : (nextProps.assetsTabs[0] || {}).key
    });
  }

  componentDidUpdate(prevProps) {
    if (!this.initShowMax) {
      this.initShowMax = this.getDefaultPreview();
    }
  }

  /**
   * 设置预览第一个资源
   */
  getDefaultPreview = () => {
    const { data, assetsTabs } = this.props;
    let allFiles = [];
    assetsTabs.map(e => allFiles = [...allFiles, ...e.multiple ? data[e.key] || [] : data[e.key] ? [data[e.key]] : []]);
    return allFiles.some(e => {
      const name = e.url;
      const filePrefix = name.substring(name.lastIndexOf('.') + 1);
      if (filePrefix && assets[filePrefix] && ['image', 'video'].includes(assets[filePrefix].type)) {
        this.handlePreview(e);
        return true;
      }
      return e;
    });
  };
  /**
   * 资源类型Tab页切换
   * @param {*} index
   * @param {*} key
   */
  handleTabChange = (index, key) => {
    this.setState({
      activeKey: key
    });
  };
  /**
   * 点击资源文件，顶部预览
   * @param {*} file 资源文件
   */
  handlePreview = (file) => {
    const name = file.url;
    const filePrefix = name.substring(name.lastIndexOf('.') + 1);
    this.setState({
      preview: { type: assets[filePrefix].type, file }
    }, () => {
      this.initShowMax = true;
      if (filePrefix === 'flv') {
        file.url && this.reloadFlvPlayer(file.url);
      } else if (filePrefix === 'mp4') {
        file.url && this.reloadMp4Player(file.url);
      } else {
        this.mp4Player && this.mp4Player.destroy();
        this.mp4Player = null;
        this.mp4Player && this.flvPlayer.destroy();
        this.flvPlayer = null;
      }
    });
  };
  /**
   * 加载FLV格式视频
   * @param {*} flvUrl
   */
  reloadFlvPlayer = (flvUrl) => {
    // 1.销毁其他播放器
    this.mp4Player && this.mp4Player.destroy();
    if (this.flvPlayer) {// 2.有播放器则切换视频源
      this.flvPlayer.src = flvUrl;
    } else {// 3.没有则new
      this.flvPlayer = new FlvPlayer({
        id: 'AssetsUpladPreviewMedia',
        url: flvUrl,
        videoInit: true,
        autoplay: true,
        controls: true,
        width: '100%',
        height: '100%'
      });
    }
  };
  /**
   * 加载MP4格式视频
   * @param {*} mp4Url
   */
  reloadMp4Player = (mp4Url) => {
    console.log(this.flvPlayer);
    // 1.销毁其他播放器
    this.flvPlayer && this.flvPlayer.destroy();
    if (this.mp4Player) {// 2.有播放器则切换视频源
      this.mp4Player.src = mp4Url;
    } else {// 3.没有则new
      this.mp4Player = new Player({
        id: 'AssetsUpladPreviewMedia',
        url: mp4Url,
        videoInit: true,
        autoplay: true,
        controls: true,
        width: '100%',
        height: '100%'
      });
    }
  };
  /**
   * 文件资源下载
   * @param {*} data
   */
  handleDownFile = (data) => {
    const a = window.document.createElement('a');
    a.href = data.url;
    a.download = data.name;
    a.target = '_blank';
    a.click();
    window.URL.revokeObjectURL(a.href);
  };
  /**
   * 文件资源删除
   * @param {*} event
   * @param {*} imageData 删除的资源
   * @param {*} item 删除资源类型项
   */
  handleDelete = (event, imageData, item) => {
    event.stopPropagation();
    const { data, onChange } = this.props;
    if (!item.multiple) {
      data[item.key] = undefined;
    } else {
      data[item.key] = (data[item.key] || []).filter(e => e.url !== imageData.url);
    }
    if ((data[item.key] || []).length === 0) {
      this.setState({ preview: {} });
    } else {
      const _file = data[item.key][0];
      const suffix = _file.url.substring(_file.url.lastIndexOf('.') + 1);
      const type = (assets[suffix] || {}).type;
      this.setState({ preview: { type, file: _file } });
    }
    onChange(item.key, data[item.key]);
  };
  /**
   * 添加资源
   * @param {*} item
   * @param {*} imageData
   */
  handleAdd = (item, imageData) => {
    const { data, onChange } = this.props;
    if (!item.multiple) {
      data[item.key] = imageData;
    } else {
      if (data[item.key] && data[item.key].length > 0) {
        data[item.key].push(imageData);
      } else {
        data[item.key] = [imageData];
      }
    }
    const suffix = imageData.url.substring(imageData.url.lastIndexOf('.') + 1);
    const type = (assets[suffix] || {}).type;
    imageData.type = type;
    this.setState({ preview: { type, file: imageData } });
    onChange(item.key, data[item.key]);
  };
  /**
   * 调用上传接口前文件校验
   * @param {*} file
   * @param {*} item
   */
  handleBeforeUpload = (file, item) => {
    if (item.check) {
      let result = file.name.split('.');
      if (!item.check.includes(result[result.length - 1])) {
        item.tip && Tip.warning(item.tip);
        return false;
      }
    }
    if (item.maxSize) {
      const isLtM = file.size / oneMb / oneMb < item.maxSize;
      if (!isLtM) {
        item.tip && Tip.warning(item.tip);
        return false;
      }
    }
    return true;
  };
  /**
   * 点击上传
   * @param {*} info
   * @param {*} item
   */
  handleUpload = (info, item) => {
    const status = info.file.status;
    this.setState({ fileList: info.fileList });
    if (status !== 'uploading') {
      if (status === 'error') {
        Tip.error('服务器发生错误');
      } else {
        const response = info.file.response;
        payload(response).then(d => {
          let key0 = Object.keys(d || {})[0];
          let key0Value = (d || {})[key0];
          d && this.handleAdd(item, { url: key0, name: key0Value });
        }).catch(Tip.error);
      }
    }
  };
  /**
   * 渲染资源tab页下的每一个资源
   * @param {*} item
   * @param {*} data
   */
  renderImage = (item, data) => {

    let sfString = !item.url ? item.rUrl ? item.rUrl : '' : item.url;
    const suffix = sfString.substring(sfString.lastIndexOf('.') + 1);
    const type = (assets[suffix] || {}).type;
    const deleteCom = this.props.type !== 'look' && data.key !== 'all' ? (
      <div className="ts-assets-item-veiw-close" onClick={(event) => this.handleDelete(event, item, data)}>
        <img src={ImageConst.common.close} alt=""/>
      </div>
    ) : null;

    if (item && item.url){
      if (type === 'file') {
        return (
          <div className="ts-file-item-veiw" key={item.url} onClick={() => this.handleDownFile(item, data)}>
            <div className="ts-assets-item-veiw-img">
              {deleteCom}
              <img src={assets[suffix].image} alt=""/>
            </div>
            <div className="ts-assets-item-veiw-name" title={item.name}>{item.name}</div>
          </div>
        );
      } else if (type === 'image') {
        return (
          <div className="ts-image-item-veiw" key={item.url} onClick={() => this.handlePreview(item, data)}>
            <div className="ts-assets-item-veiw-img">
              {deleteCom}
              <img src={item.url || item.thumbUrl} alt=""/>
            </div>
            <div className="ts-assets-item-veiw-name" title={item.name}>{item.name}</div>
          </div>
        );
      } else if (type === 'video') {
        return (
          <div className="ts-file-item-veiw" key={item.url} onClick={() => this.handlePreview(item, data)}>
            <div className="ts-assets-item-veiw-img">
              {deleteCom}
              <img src={assets[suffix].image} alt=""/>
            </div>
            <div className="ts-assets-item-veiw-name" title={item.name}>{item.name}</div>
          </div>
        );
      } else {
        return (
          <div className="ts-file-item-veiw" key={item.url}>
            <div className="ts-assets-item-veiw-img">
              {deleteCom}
            </div>
            <div className="ts-assets-item-veiw-name" title={item.name}>{item.name}</div>
          </div>
        );
      }
    } else {
      return (
        <div />
      );
    }




  };
  /**
   * 渲染一个资源Tab页面的所有内容
   * @param {*} item
   * @param {*} value
   */
  renderContent = (item, value) => {
    const uploadProps = {
      accept: item.accept,
      multiple: item.multiple,
      showUploadList: false,
      fileList: this.state.fileList,
      beforeUpload: (file) => this.handleBeforeUpload(file, item),
      action: UrlConsts.platFormUploadfileUrl(),
      onChange: (file) => this.handleUpload(file, item),
      headers: compleHeaders()
    };
    console.log('------->', value);
    return (
      <div className="ts-com-assetsuplad-list">
        {
          item.key !== 'all' && !(this.props.type === 'look' || item.auth === 'look') && <Upload {...uploadProps}>
            <div className="ts-com-assetsuplad-btn">
              <div className="ts-com-assetsuplad-btn-icon">
                <img src={ImageConst.common.add} alt=""/>
              </div>
              <p className="ts-com-assetsuplad-btn-text">上传</p>
            </div>
          </Upload>
        }
        {
          (value || []).map(e => this.renderImage(e, item))
        }
      </div>
    );
  };

  render() {
    debugger
    const { assetsTabs, data } = this.props;
    const { activeKey, preview } = this.state;

    let allFiles = [];
    assetsTabs.map(e => allFiles = [...allFiles, ...e.multiple ? data[e.key] || [] : data[e.key] ? [data[e.key]] : []]);
    return (
      <div className="ts-com-assetsuplad mod-com-scrollbar">
        <div className="ts-com-assetsuplad-preview">
          <div className="ts-com-assetsuplad-preview-content">
            {preview.type === 'image' && <img src={(preview.file || {}).url} alt=""/>}
            {preview.type === 'video' && <div id="AssetsUpladPreviewMedia"/>}
          </div>
          <div className="ts-com-assetsuplad-preview-footer">{(preview.file || {}).name} </div>
        </div>
        <div className="ts-com-assetsuplad-tabs">
          <Tabs mode="line" className="mods-com-linetab" activeKey={activeKey} onChange={this.handleTabChange}>
            <TabList>
              {assetsTabs.length > 1 && <Tab key="all" activeKey="all">全部</Tab>}
              {assetsTabs.map(item => <Tab key={item.key} activeKey={item.key}>{item.title}</Tab>)}
            </TabList>
            <TabPanel key="all" activeKey="all">
              {this.renderContent({ key: 'all' }, allFiles)}
            </TabPanel>
            {
              assetsTabs.map(item => (
                <TabPanel key={item.key} activeKey={item.key}>
                  {this.renderContent(item, data[item.key])}
                </TabPanel>
              ))
            }
          </Tabs>
        </div>
      </div>
    );
  }
}

export default AssetsUpload;
