/**
 * @Author: wanghaofeng
 * @date: 2020/11/19 10:25
 * @Description：公共文件夹复制弹窗
 */

import React from 'react'; 
import { Modal, Button, Breadcrumb, Radio, message  } from 'antd';
import Service from '@/common/js/service';
import { FILE_TYPE_ICON_MAP, DEFAULT_SIZE_UNIT } from "@/domains/resource-disk/constants";
import { LottieIcon } from 'xiaomai-b-components';
import _ from 'underscore';
import { getEllipsText } from "@/domains/basic-domain/utils";
import * as lodash from 'lodash';
import './CopyFileModal.less';
import User from '@/common/js/user';
window.currentUserInstInfo = {adminId: "1224977437688578050", adminName: "吴帆", gender: "UNKNOWN", parentId: "1224977437688578050", nickName: "吴帆", name: "5.0项目测试第七校区", instId: "1199660913171755009" }

const { instId } = window.currentUserInstInfo;     // 机构Id
const folder_list_url = {                          // 文件夹url                     
  'MYSELF': 'public/hadesStore/folderList',               
  'COMMON': 'public/hadesStore/folderList'
}
const defaultQuery = {                             // 默认请求参数
  size: 10,
  current: 1,
  folderIdType: 'FOLDER'
}
const defaultFolderPathList = [                    
  {
    disk : "COMMON",
    folderName : "公共文件"
  },
  {
    disk : "MYSELF",
    folderName : "我的文件"
  }
]

class CopyFileModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      folderPathList : [],                         // 文件储存路径
      currentFolder : [],                          // 当前文件
      folderList : [],                             // 信息列表
      aid :  localStorage.getItem('aid'),          // aid
      query : defaultQuery,                        // 初始化请求参数
      totalCount : 0,                              // 但前页面加载数据总数
      pages: 1,                                    // 获取信息总页数，默认为1页
      showLottieIcon: true,
      disk: this.props.currentRootDisk.disk,
    }
    this.fileListRef = React.createRef();
  }

  componentWillMount() {
    this.setState({
      // 默认打开为公共文件夹
      folderPathList : [defaultFolderPathList[0]],
    })
  }

  componentDidMount() {
    this.getFileList('COMMON');
  }

  // 关闭弹窗/取消复制
  handleClose = () => {
    this.setState({
      folderPathList : [defaultFolderPathList[0]]
    },() => {
      this.props.onClose();
    })
  }

  // 点击确认复制
  confirmCopy = () => {
    // const { folderPathList, folderList } = this.state;
    const { folderPathList, disk } = this.state;
    const { dataInfo } = this.props;
    const { id, createId, folderName } = dataInfo;
    const newParentId = folderPathList[folderPathList.length-1].id;
    const _params = {
      copyIds : [id],                     // 复制文件的ID
      newParentId,                      // 新的父节点ID
      instId,                           // 机构ID
      disk,                             // 盘符
      createId: User.getUserId(),                         // 创建者ID
    }

    // 判断目标文件夹是否是其自身或者是他的子文件夹
    let allowCopy = 0;          
    folderPathList.map((item) => {
      if (item.folderName === folderName) {
        allowCopy = 1;
        message.warning('不能将文件复制到自身或其子目录下')
      }
      return allowCopy;
    })
    
    if (allowCopy === 0) {
      Service.Hades('public/hadesStore/copyFolder', _params).then((res) => {
        if (res.success) {
          message.success('复制成功');
          this.getFileList(disk, newParentId);
        }
      })
    }
  }

  // 点击面包屑
  changeFolderPath = (folderPath) => {
    const { folderPathList, folderList } = this.state;
    const { disk } = folderPathList[0];
    const { id } = folderPath;
    // 当前页page设置为1
    const query = _.clone(this.state.query);
    query.current = 1;            
    this.setState({ query });

    // 判断被点击文件夹是否存在父级文件夹
    const _parentId = (folderList.length && folderList[0].parentId) ? id : null;

    // 获取新的文件路径列表
    let _folderPathList = JSON.parse(JSON.stringify(folderPathList));
    folderPathList.map((item, index) => {
      if (folderPath.folderName === item.folderName) {
        _folderPathList.splice(index + 1);
      } 
      return _folderPathList;
    })
    // 刷新数据
    this.setState({
      folderPathList : _folderPathList,
      query
    }, () => {
      this.getFileList(disk, _parentId);
    })
    
  }

  // 点击文件夹
  handleSelect = (folder) => { 
    const { folderType, id, folderName } = folder;
    const { folderPathList } = this.state;
    const disk = folderPathList[0].disk;
    let _folderPathList = JSON.parse(JSON.stringify(folderPathList));
    const query = _.clone(this.state.query);
    query.current = 1;            

    // 选择文件，直接返回
    if (folderType !== 'FOLDER') return;
    // 选择的是文件夹,更新文件路径
    _folderPathList.push({
      id,
      folderName
    });
    this.setState({
      folderPathList : _folderPathList,
      query
    },() => {
      this.getFileList(disk, id, folderType);
    })
  }

  // 获取信息列表
  getFileList = (disk, parentId=null, folderType='FOLDER', hasMore = false) => {
    const { current, size } = this.state.query;
    const { folderPathList, folderList } = this.state;
    // 如果不是文件夹，直接return
    if (folderType !== 'FOLDER') return;
    const _params = {
      disk,
      parentId,
      current,
      size,
      folderIdType : folderType,
      storeId:User.getStoreId(),
      createId:User.getUserId()
    }
    // 是否切换盘符
    if (folderPathList[0].disk !== disk){
      if (disk === 'COMMON') {
        this.setState({folderPathList : [defaultFolderPathList[0]]});
      } else {
        this.setState({folderPathList : [defaultFolderPathList[1]]});
      }
    }
    this.setState({ disk });
    Service.Hades(folder_list_url[disk], _params).then((res) => {
      if (res.result) {
        if (hasMore) {            // 是否是由滑动获取更多触发
          const _folderList = JSON.parse(JSON.stringify(folderList)).concat(res.result.records);
          this.setState({
            pages : res.result.pages,
            folderList : _folderList,
            totalCount : res.result.total
          })
        } else {
          this.setState({
            pages : res.result.pages,
            folderList : res.result.records,
            totalCount : res.result.total
          })
        }
      }
    }) 
  }

  // 滑动加载更多
  handleScrollEvent = () => {
    const { folderList, totalCount, folderPathList, pages } = this.state;
    // 判断是否还有更多信息
    const hasMore = folderList.length < totalCount;  
    // 判断滑动到最下面
    const hasReachBottom = (this.fileListRef.current.scrollTop + this.fileListRef.current.clientHeight) > this.fileListRef.current.scrollHeight - 1;
    if (!hasReachBottom || !hasMore) return;

    const query = _.clone(this.state.query);
    if (query.current < pages) {
      query.current = query.current + 1;            // 修改当前页为下一页
      const disk = folderPathList[0].disk;
      const parentId = folderList[0].parentId;

      this.setState({ query }, () => {
        this.getFileList(disk, parentId, 'FOLDER', true);
      })
    }
  }

  render() {
    const { isOpen } = this.props;
    const { folderList, folderPathList, showLottieIcon } = this.state;
    const title = '复制到';

    return (
      <Modal
        visible={isOpen}
        title={title}
        width={680}
        onCancel={this.handleClose}
        maskClosable={false}
        footer={[
          <Button key="back" onClick={this.handleClose}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={this.confirmCopy}>
            复制到此目录
          </Button>
        ]}
        closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
      >
      <div className='copy-body'>
        {/* 面包屑 */}
        <div className="bread-crumbs">
          <Breadcrumb>
            {
              folderPathList.map((item, index) => {
                return (
                  <Breadcrumb.Item key={index}>
                    {
                      // 判断是不是最后一项 
                      (index !== folderPathList.length - 1) &&
                      <span 
                        className='bread' 
                        onClick={() => this.changeFolderPath(item)}
                      >
                        {item.folderName}
                      </span>
                    }
                    {
                      // 最后一项不给绑定点击事件
                      !(index !== folderPathList.length - 1) &&
                      <span>{item.folderName}</span>
                    }
                  </Breadcrumb.Item>
                )
              })
            }
          </Breadcrumb>
        </div>
        {/* 信息列表 */}
        {
          (folderList.length>0) &&
          <div>
            <div className='folder-list'
               onScrollCapture={() => this.handleScrollEvent()}
               style={{ height: '320px', overflowY: 'scroll' }}
               ref={this.fileListRef}
            >
            {
              folderList.map(item => {
                const { folderType, folderFormat, folderSize } = item;

                const isFolder = folderType === 'FOLDER';                           // 是否是文件夹
                let _size = `${(folderSize / DEFAULT_SIZE_UNIT).toFixed(1)}M`;      // 文件大小        
                if (folderSize < 0.1 * DEFAULT_SIZE_UNIT) {
                  _size = `${(folderSize / 1024).toFixed(1)}kb`;
                }
                let imgSrc = !isFolder ?                                           // 文件/文件夹图标
                  FILE_TYPE_ICON_MAP[folderFormat] :
                  'https://xiaomai-image.oss-cn-hangzhou.aliyuncs.com/1594871430788.png';
                if(isFolder){
                  return (
                    <div 
                      className={`information ${isFolder ? 'enable' : 'disable'}`}
                      key={item.id} 
                      onClick={lodash.debounce(() => this.handleSelect(item), 500)}
                    >
                      <img src={imgSrc} alt="file-item__img" height="24"/>
                      <span className='folderName'>{getEllipsText(item.folderName, 20)}</span>
                      {
                        isFolder &&
                        <div className="file-item__expend-icon">
                          <span className="icon iconfont">&#xe71b;</span>
                        </div>
                      }
                      { !isFolder && <div className="file-item__size">{_size}</div> }
                    </div>
                  )
                }
              })
            }
            </div>
          </div>
        }
        {
          !(folderList.length>0) && showLottieIcon &&
          <div className="lottie-box">
            <LottieIcon
              title={<span className="desc">这个文件夹是空的</span>}
            />
          </div>
        }
      </div>
      </Modal>
    )
  }
}

export default CopyFileModal;
