/*
 * @Author: 吴文洁 
 * @Date: 2020-06-09 09:47:44 
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-05-08 10:46:44
 * @Description: 文件夹管理
 */

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

import Service from '@/common/js/service';
import { SUFFIX_MAP } from '@/domains/resource-disk/constants';
import User from '@/common/js/user';
import OperateArea from './OperateArea';
import FolderList from './FolderList';



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

export const getFileTypeByName = (name) => {
  const nameArray = name.split(".");
  const suffix = nameArray[nameArray.length - 1];
  return SUFFIX_MAP[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: [],                  // 已被选择的文件
      selectedFileRights: [],               // 已被选择的文件对应权限
      folderList: [],                       // 当前目录下的文件
      searchKey: null,                      // 搜索关键字
      totalCount: 0,                        // 该磁盘总共有的文件个数
      showResultPage: false,                // 是否显示结果页
      loading: false,                       // 是否正在请求数据
      hasManagementAuthority: true,         // 是否有管理者权限
      query: defaultQuery,                  // 文件列表的初始请求条件
      _parentRights: '',                    // 父级文件夹权限
    }
  }

  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: [],      // 切换目录后，取消勾选已经选择的文件
        selectedFileRights: []
      }, () => {
        this.handleFetchFolderList();
      });
    }
  }

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

    //TODO
    this.handleFetchFolderList();
  }

  // 请求当前目录下的文件列表
  handleFetchFolderList = (params = {}, isSearch = false) => {
    this.setState({
      loading: true
    }, () => {
      const { parentRights } = params;
      const { showResultPage, searchName, query, _parentRights } = this.state;
      const { current } = query;
      const {
        currentRootDisk: { disk }
      } = this.props;

      const _params = {
        ...query,
        ...params,
        parentRights,
        disk,
        searchName: showResultPage ? searchName : null,
        storeId:User.getStoreId(),
        createId:User.getUserId()
      }
      _params.current = isSearch ? 1 : current;

      if (parentRights) {
        this.setState({ _parentRights: parentRights },()=>{
          Service.Hades(FOLDERLIST_URL_MAP[disk], _params).then((res) => {
            const { result = {} } = res;
            const { records = [], total = 0 } = result;
            let _records = [];
            
            // 判断是否继承了父级文件权限
            if (records.length > 0 && !records[0].rights) {
              records.map((item,index) => {
                item.rights = parentRights;
                _records.push(item);
                return _records;
              })
              this.setState({
                loading: false,
                folderList: _records,
                totalCount: Number(total),
                selectedFileIds: [],      // 删除之后需要将已经选择的文件清空
                selectedFileRights: []
              });
            } else {
              this.setState({
                loading: false,
                folderList: records,
                totalCount: Number(total),
                selectedFileIds: [],      // 删除之后需要将已经选择的文件清空
                selectedFileRights: []
              });
            }
          }).catch((error)=>{
            this.setState({
              loading: false,
            })
              });
        });
      } else {
        Service.Hades(FOLDERLIST_URL_MAP[disk], _params).then((res) => {
          const { result = {} } = res;
          const { records = [], total = 0 } = result;
          let _records = [];
          
          // 判断是否继承了父级文件权限
          if (records.length > 0 && !records[0].rights) {
            records.map((item,index) => {
              item.rights = _parentRights;
              _records.push(item);
              return _records;
            })
            this.setState({
              loading: false,
              folderList: _records,
              totalCount: Number(total),
              selectedFileIds: [],      // 删除之后需要将已经选择的文件清空
              selectedFileRights: []
            });
          } else {
            this.setState({
              loading: false,
              folderList: records,
              totalCount: Number(total),
              selectedFileIds: [],      // 删除之后需要将已经选择的文件清空
              selectedFileRights: []
            });
          }
        }).catch((error)=>{
          this.setState({
            loading: false,
          })
            });
      }
      

    })
  }

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

  handleChangeRow = (selectedRowKeys) => {
    const { folderList } = this.state;
    let _selectedFileRights = [];
    selectedRowKeys.map(folderId => {
      folderList.map(item => {
        if (item.id === folderId) {
          _selectedFileRights.push(item.rights);
        }
        return _selectedFileRights;
      })
      return _selectedFileRights;
    })
    this.setState({
      selectedFileIds: selectedRowKeys,
      selectedFileRights: _selectedFileRights
    })
  }

  // 上传完成之后，添加到文件夹
  handleUploadDone = (file, resourceId, uploadFolderPath,optionType) => {
    const { currentRootDisk } = this.props;
    const { 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,
      createUser:"STORE_USER",
      parentId: id,
      storeId:User.getStoreId(),
      createId:User.getUserId()
    }
    Service.Hades('public/hadesStore/saveFolder', params).then((res) => {
      if(optionType === "addFolder"){
        message.success("创建文件夹成功！");
      }
      const query = _.clone(this.state.query);
      query.current = 1;
      this.setState({ query }, () => {
        if (resourceId && !_.isEqual(uploadFolderPath, currentFolder)) return;
        this.handleFetchFolderList({ parentId: id });
      });
    });
  }

  // 移动文件
  handleMove = (query, sourceFileIds = this.state.selectedFileIds) => {
    const { targetFolder, selectFolderPathList } = query;
    const { currentRootDisk: { disk} } = this.props;
    const { folderPathList } = this.state;
    const currentFolder = folderPathList[folderPathList.length - 1];
    const { id } = targetFolder;
    // 将selectedFileIds移动到targetFolder
    let params = {
      disk,
      moveIds: sourceFileIds,
      storeId:User.getStoreId(),
      createId:User.getUserId()
    }
    if (selectFolderPathList.length > 1) {
      params.newParentId = id
    }
    Service.Hades('public/hadesStore/moveFolder', params).then((res) => {

      // 判断是否将文件移动到了自身或者子目录
      const { result = {} } = res;
      const { code, message: _message } = result;
      if (code === 'PARAM_ERROR') {
        message.warning(_message);
        return;
      }
      if (id == null) {
        Modal.success({
          title: '文件移动成功',
          content: '移动到一级目录的文件仅自己可以查看，如需其他成员查看请设置权限'
        })
      } else {
        message.success('文件移动成功');
      }

      // 移动成功之后需要将selectedFileIds置为空
      this.setState({ selectedFileIds: [] });
      this.handleFetchFolderList({ parentId: currentFolder.id, current: 1});
    })
  }
  
  // 修改文件路径
  handleChangeFolderPath = (folderPathList, hasRootDisk = true) => {
    // 点击列表页的‘所在目录’，获取的目录是不带根目录的，所以要区分处理
    const { currentRootDisk } = this.props;
    const { disk } = currentRootDisk;
    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
      }
    }, () => {
      if (disk !== "COMMON") {
        this.handleFetchFolderList({
          parentId: id,
          folderIdType: employeeDisk ? 'USER' : 'FOLDER'
        });
      } else {
        this.handleFetchFolderList({
          parentRights: this.state._parentRights,
          parentId: id,
          folderIdType: employeeDisk ? 'USER' : 'FOLDER'
        });
      }
    })    
  }

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

  // 翻页
  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;
      _query.size = value;
    }
    
    this.setState({ query: _query }, () => {
      this.handleFetchFolderList({
        folderIdType: employeeDisk ? 'USER' : 'FOLDER',
        parentId: currentFolder.id
      });
    })
  }

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

    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}
            selectedFileRights={selectedFileRights}

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

          {/* 文件夹列表 */}
          <FolderList
            query={query}
            totalCount={totalCount}
            balance={balance}
            showResultPage={showResultPage}
            currentRootDisk={currentRootDisk}
            hasManagementAuthority={hasManagementAuthority}
            
            folderList={folderList}
            folderPathList={folderPathList}
            selectedFileIds={selectedFileIds}

            onChangeRow={this.handleChangeRow}
            onChangeFolderPath={this.handleChangeFolderPath}
            onMove={this.handleMove}
            onUpload={this.handleUploadDone}
            onChangePage={this.handleChangePage}
            onRefresh={this.handleFetchFolderList}
          />
        </div>
      </Spin>
      
    )
  }
}

export default withRouter(FolderManage);