/*
 * @Author: 吴文洁 
 * @Date: 2020-06-09 09:47:44 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-16 17:53:33
 * @Description: 文件夹管理
 */

import React from 'react';
import { withRouter } from 'react-router-dom';
import { Spin, message } from 'antd';

import User from '@/common/js/user';

import OperateArea from './OperateArea';

import { DISK_MAP, suffixMap } from "@/common/constants/academic/lessonEnum";

const FOLDERLIST_URL_MAP = {
  'MYSELF': 'public/apollo/folderList',
  'COMMON': 'public/apollo/commonFolderList',
  'EMPLOYEE': 'public/apollo/employeeFolderList'
};

export const getFileTypeByName = (name) => {
  const nameArray = name.split(".");
  const suffix = nameArray[nameArray.length - 1];
  return suffixMap[suffix];
}

const defaultQuery = {
  size: 10,
  current: 1,
  folderIdType: 'FOLDER'
}

class FolderManage extends React.Component {

  constructor(props) {
    super(props);
    const showTips = localStorage.getItem('showTips');
    this.state = {
      showTips,
      folderPathList: [props.currentRootDisk],
      selectedFileIds: [],          // 已被选择的文件
      folderList: [],               // 当前目录下的文件
      searchKey: null,              // 搜索关键字
      totalCount: 0,                // 该磁盘总共有的文件个数
      showResultPage: false,        // 是否显示结果页
      loading: false,               // 是否正在请求数据
      hasManagementAuthority: true, // 是否有管理者权限
      query: defaultQuery,          // 文件列表的初始请求条件
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!_.isEqual(nextProps.currentRootDisk, this.props.currentRootDisk) ||
      nextProps.match.path !== this.props.match.path) {
      this.setState({
        showResultPage: false,
        query: defaultQuery,
        folderPathList: [nextProps.currentRootDisk],
        selectedFileIds: [],  // 切换目录后，取消勾选已经选择的文件
      }, () => {
        this.handleFetchFolderList();
      });
    }
  }

  componentDidMount() {
    // 校验余额（欠费的情况下限制上传文件）
    this.handleCheckBalance();
  }

  // 请求当前目录下的文件列表
  handleFetchFolderList = (params = {}) => {
    this.setState({
      loading: true
    }, () => {
      const { showResultPage, searchName } = this.state;
      const { currentRootDisk: { disk } } = this.props;
      const { instId } = window.currentUserInstInfo;
      
      const _params = {
        ...this.state.query,
        ...params,
        searchName: showResultPage ? searchName : null,
        disk,
        instId: instId || LS.get('instId'),
      }
      axios.Apollo(FOLDERLIST_URL_MAP[disk], _params).then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0 } = result;
        this.setState({
          loading: false,
          folderList: records,
          totalCount: Number(total),
          selectedFileIds: [],      // 删除之后需要将已经选择的文件清空
        });
      });
    })
  }

  // 搜索
  handleSearch = (value) => {
    if (!value) return;
    const { currentRootDisk } = this.props;
    const folderPathList = [currentRootDisk, {
      folderName: `搜索"${value}"`
    }]
    this.setState({
      searchName: value,
      folderPathList,
      showResultPage: true
    }, () => {
      // 根据关键字搜索结果页文件列表
      this.handleFetchFolderList();
    });
  }

  handleChangeRow = (selectedRowKeys) => {
    this.setState({
      selectedFileIds: selectedRowKeys
    })
  }

  // 上传完成之后，添加到文件夹
  handleUploadDone = (file, resourceId, uploadFolderPath) => {
    const { currentRootDisk } = this.props;
    const { folderList, folderPathList } = this.state;

    const { teacherId, instId } = window.currentUserInstInfo;
    const currentFolder = folderPathList[folderPathList.length - 1];
    const { id = null } = uploadFolderPath || currentFolder;
    let { size, type, name } = file;

    if (!type) {
      type = getFileTypeByName(name)
    }

    const params = {
      name,
      resourceId,
      folderSize: size,
      folderFormat: type,
      folderTypeEnum: resourceId ? 'FILE' : 'FOLDER',
      disk: currentRootDisk.disk,
      instId: instId || LS.get('instId'),
      createUser: teacherId ? "TEACHER" : "ADMIN",
      parentId: id
    }

    axios.Apollo('public/apollo/saveFolder', params).then((res) => {
      const query = _.clone(this.state.query);
      query.current = 1;
      this.setState({ query }, () => {
        if (resourceId && !_.isEqual(uploadFolderPath, currentFolder)) return;
        this.handleFetchFolderList({ parentId: id });
      });
    });
  }

  // 移动文件
  handleMove = (targetFolder, sourceFileIds = this.state.selectedFileIds) => {
    const { currentRootDisk: { disk} } = this.props;
    const { folderPathList } = this.state;
    const currentFolder = folderPathList[folderPathList.length - 1];
    const { id } = targetFolder;
    // 将selectedFileIds移动到targetFolder
    const params = {
      disk,
      moveIds: sourceFileIds,
      newParentId: id,
    }

    axios.Apollo('public/apollo/moveFolder', params).then((res) => {

      // 判断是否将文件移动到了自身或者子目录
      const { result = {} } = res;
      const { code, message: _message } = result;
      if (code === 'PARAM_ERROR') {
        message.warning(_message);
        return;
      }

      // 移动成功之后需要将selectedFileIds置为空
      message.success('文件移动成功');
      this.setState({ selectedFileIds: [] });
      this.handleFetchFolderList({ parentId: currentFolder.id});
    })
  }
  
  // 修改文件路径
  handleChangeFolderPath = (folderPathList, hasRootDisk = true) => {
    // 点击列表页的‘所在目录’，获取的目录是不带根目录的，所以要区分处理
    const { currentRootDisk } = this.props;
    const _folderPathList =  hasRootDisk ? folderPathList :  [currentRootDisk, ...folderPathList];
    this.setState({
      showResultPage: false,
      folderPathList: _folderPathList,
    });
    
    // 重新获取对应目录下的文件
    const currentFolder = _folderPathList[_folderPathList.length - 1];
    const { id = null } = currentFolder;
    // 判断是否是员工文件的根目录
    const employeeDisk = currentRootDisk.disk === 'EMPLOYEE' && folderPathList.length === 2;

    this.setState({
      query: {
        ...this.state.query,
        current: 1
      }
    }, () => {
      this.handleFetchFolderList({
        parentId: id,
        folderIdType: employeeDisk ? 'USER' : 'FOLDER'
      });
    })    
  }

  // 校验余额
  handleCheckBalance = async () => {
    const { instId } = window.currentUserInstInfo;
    const balanceRes = await axios.Business("public/liveAssets/query", { instId });
    const { result } = balanceRes;
    this.setState({
      balance: result ? result.balance : 0
    })
  };

  // 翻页
  handleChangePage = (field, value) => {
    const { query, folderPathList } = this.state;
    const { currentRootDisk } = this.props;
    const employeeDisk = currentRootDisk.disk === 'EMPLOYEE' && folderPathList.length === 2;
    // 重新获取对应目录下的文件
    const currentFolder = folderPathList[folderPathList.length - 1];
    
    const _query = _.clone(query);
    _query[field] = value;
    if (field === 'size') {
      _query.current = 1;
    }
   
    this.setState({ query: _query }, () => {
      this.handleFetchFolderList({
        folderIdType: employeeDisk ? 'USER' : 'FOLDER',
        parentId: currentFolder.id
      });
    })
  }

  render() {
    
    const {
      selectedFileIds, searchKey, query,
      folderPathList, folderList, totalCount,
      showResultPage, showTips, loading,
      hasManagementAuthority, balance
    } = this.state;

    const { current } = query;
    const { currentRootDisk } = this.props;
    
    return (
      <Spin spinning={loading} style={{width: '100%'}}>
        <div className="folder-manage">
          {/* 只有‘我的文件’才显示提示文案 */}
          {
            currentRootDisk.disk === 'MYSELF' && !showTips &&
            <div
              className="tips"
            >
              <span className="tips__text">管理者有权限查看员工个人文件</span>
              <span
                className="icon iconfont"
                onClick={() => {
                  this.setState({ showTips: true });
                  localStorage.setItem('showTips', true);
                }}
              >&#xe6ef;</span>
            </div>
          }

          {/* 操作区：新建文件夹、上传文件、批量移动、批量删除和搜索 */}
          <OperateArea
            balance={balance}
            searchKey={searchKey}
            currentRootDisk={currentRootDisk}
            showResultPage={showResultPage}
            hasManagementAuthority={hasManagementAuthority}

            folderPathList={folderPathList}
            selectedFileIds={selectedFileIds}

            onMove={this.handleMove}
            onSearch={this.handleSearch}
            onCreate={this.handleUploadDone}
            onChangeFolderPath={this.handleChangeFolderPath}
            onRefresh={this.handleFetchFolderList}
          />
        </div>
      </Spin>
      
    )
  }
}

export default withRouter(FolderManage);