/*
 * @Author: 吴文洁
 * @Date: 2020-06-22 14:26:37
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-06-08 18:18:46
 */
import PreviewFileModal from '@/bu-components/PreviewFileModal';
import { FileTypeIcon, FileVerifyMap } from '@/common/constants/academic/lessonEnum';
import { DEFAULT_SIZE_UNIT, suffixType } from '@/common/constants/academic/liveEnum';
import Service from '@/common/js/service';
import User from '@/common/js/user';
import college from '@/common/lottie/college';
import { XMTable } from '@/components';
import BaseService from '@/domains/basic-domain/baseService';
import { YZ_APPId, YZ_PREVIEW_URL } from '@/domains/basic-domain/constants';
import ScanFileModal from '@/modules/prepare-lesson/modal/ScanFileModal';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import { LoadingOutlined } from '@ant-design/icons';
import { Button, message, Modal, Popconfirm, Spin, Tooltip } from 'antd';
import Lottie from 'lottie-web';
import moment from 'moment';
import React from 'react';
import _ from 'underscore';
import './ManageCoursewareModal.less';

class ManageCoursewareModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      uploadObject: {},
      failObject: {},
      cancelObject: {},
      editData: {},
      scanFileModal: false,
      isLessonPermission: false,
      diskList: [], // 机构可见的磁盘目录
      selectedFileList: [],
      showPreviewModal: false, //是否显示loading
      previewing: false, //是否正在预览
      previewStatus: 'UPLOAD', //预览文件的生成状态
    };
  }

  componentDidMount() {
    this.getCoursewareList();
    var animation = Lottie.loadAnimation({
      path: 'https://image.xiaomaiketang.com/xm/SDBkP7mbJX.json',
      name: 'test',
      renderer: 'svg',
      loop: true,
      autoplay: true,
      container: document.getElementById('lottie-box'),
    });
  }

  // 获取课件列表
  getCoursewareList(id) {
    const { liveCourseId } = this.props.data;
    const params = {
      liveCourseId,
      storeId: User.getStoreId(),
    };
    Service.Hades('/anon/courseWare/getCourseWareDocList', params).then((res) => {
      let newList = [];
      const { list } = this.state;
      const data = _.find(res.result, (item) => item.docId == id);
      if (id && !_.isEmpty(data)) {
        newList = list.map((item) => {
          if (item.id == id) {
            data.id = data.docId;
            if (data.fileSize > 0) {
              if (data.fileSize > 0.1 * DEFAULT_SIZE_UNIT) {
                data.fileSize = `${(data.fileSize / DEFAULT_SIZE_UNIT).toFixed(1)}M`;
              } else {
                data.fileSize = `${(data.fileSize / 1024).toFixed(1)}KB`;
              }
            } else {
              data.fileSize = '-';
              data.failState = true;
            }
            return data;
          } else {
            return item;
          }
        });
      } else {
        newList = res.result.map((item) => {
          item.id = item.docId;
          if (item.fileSize > 0) {
            if (item.fileSize > 0.1 * DEFAULT_SIZE_UNIT) {
              item.fileSize = `${(item.fileSize / DEFAULT_SIZE_UNIT).toFixed(1)}M`;
            } else {
              item.fileSize = `${(item.fileSize / 1024).toFixed(1)}KB`;
            }
          } else {
            item.fileSize = '-';
            item.failState = true;
          }
          return item;
        });
      }
      this.setState({ list: newList });
    });
  }

  // 上传文件
  addFile() {
    // 判断是否早于开课前30分钟
    const { startTime } = this.props.data;
    const currentTime = new Date().getTime();
    if (currentTime >= startTime - 30 * 60 * 1000) {
      Modal.info({
        title: '不能再上传课件了',
        icon: (
          <span className='icon iconfont default-confirm-icon' style={{ color: '#FFBB54 !important' }}>
            &#xe834;
          </span>
        ),
        content: '请在开课前30分钟前上传课件，开课后可在客户端中进行上传。',
        okText: '我知道了',
      });
      return;
    }

    const { list } = this.state;
    if (list.length >= 20) {
      message.warning('最多上传20个课件');
      return null;
    }
    this.setState({
      selectedFileList: list,
      showSelectFileModal: true, // 选择文件弹窗
    });
  }

  handleAddFile = (addFolderIds) => {
    this.setState({
      showSelectFileModal: false,
    });

    const { liveCourseId } = this.props.data;
    const params = {
      addFolderIds,
      liveCourseId,
      checkTime: true,
      operatorId: User.getUserId(),
    };
    Service.Hades('public/courseWare/uploadCourseWareFile', params).then((res) => {
      this.getCoursewareList();
    });
  };

  // 删除文件
  deleteFile(item) {
    const { list } = this.state;
    Service.Hades('public/courseWare/delCourseDoc', { docId: item.id }).then(() => {
      item.docId && message.success('删除成功');
    });
    const _list = _.reject(list, (data) => data.id == item.id);
    this.setState({ list: _list });
  }

  // 预览文件
  handleScanFile = async (item) => {
    if (!item.srcDocUrl) return null;

    const suffix = _.last(item.fileName.split('.')).toLowerCase();
    const type = suffixType[suffix];
    const fileType = FileVerifyMap[type].type;
    const that = this;
    switch (fileType) {
      case 'PDF':
      case 'Excel':
      case 'EXCEL':
      case 'PPT':
      case 'PPTX':
      case 'word':
      case 'WORD':
      case 'DOCX':
      case 'DOC':
        if (!item.fileVersionId) {
          this.setState(
            {
              previewing: true,
              showPreviewModal: true,
              previewStatus: 'UPLOAD',
            },
            async () => {
              const uploadParams = {
                fileUrl: item.srcDocUrl,
                instId: User.getStoreId(),
                yoZoTypeEnum: 'UPLOAD',
              };
              const uploadSign = await BaseService.getYoZoSign(uploadParams);
              BaseService.yoZoUpload(item.srcDocUrl, YZ_APPId, uploadSign).then(async function (response) {
                const saveParams = {
                  fileVersionId: response.data.data.fileVersionId,
                  folderId: item.folderId,
                  instId: User.getStoreId(),
                };
                BaseService.saveYoZoFileVersionId(saveParams);
                const { previewing } = that.state;
                if (previewing) {
                  const previewParams = {
                    fileVersionId: response.data.data.fileVersionId,
                    instId: User.getStoreId(),
                    yoZoTypeEnum: 'VIEW',
                    htmlTitle: item.fileName,
                  };
                  const previewSign = await BaseService.getYoZoSign(previewParams);
                  const url = `${YZ_PREVIEW_URL}?fileVersionId=${response.data.data.fileVersionId}&appId=${YZ_APPId}&sign=${previewSign}&htmlTitle=${item.fileName}`;
                  that.setState({
                    previewStatus: 'UPLOAD_SUCCESS',
                    url,
                  });
                }
              });
            }
          );
        } else {
          const previewParams = {
            fileVersionId: item.fileVersionId,
            instId: User.getStoreId(),
            yoZoTypeEnum: 'VIEW',
            htmlTitle: item.fileName,
          };
          const previewSign = await BaseService.getYoZoSign(previewParams);
          const url = `${YZ_PREVIEW_URL}?fileVersionId=${item.fileVersionId}&appId=${YZ_APPId}&sign=${previewSign}&htmlTitle=${item.fileName}`;
          const a = document.createElement('a');
          document.body.appendChild(a);
          a.setAttribute('href', url);
          a.setAttribute('target', '_blank');
          a.click();
          document.body.removeChild(a);
        }
        break;
      case 'JPG':
      case 'PNG':
      case 'MP4':
      case 'MP3':
        this.setState({ scanFileModal: true, editData: { fileType, ossAddress: item.srcDocUrl } });
        break;
      default:
        break;
    }
  };
  cancelPreview = () => {
    this.setState({
      previewing: false,
      showPreviewModal: false,
      previewStatus: 'UPLOAD',
    });
  };
  render() {
    const columns = [
      {
        title: '名称',
        width: '25%',
        dataIndex: 'name',
        render: (_value, item) => {
          const suffix = _.last(item.fileName.split('.')).toLowerCase();
          const fileType = suffixType[suffix];

          const antIcon = <LoadingOutlined />;
          const type = FileVerifyMap[fileType].type;
          return (
            <div className='courseware-name' onClick={() => this.handleScanFile(item)}>
              <Choose>
                <When condition={(type === 'JPG' || type === 'PNG') && item.progress}>
                  <Spin indicator={antIcon} />
                </When>
                <Otherwise>
                  <img src={FileTypeIcon[FileVerifyMap[fileType].type] || (item.docUrls[0] || {}).conversionFileUrl} alt='' className='item-img' />
                </Otherwise>
              </Choose>
              <Tooltip title={item.fileName}>
                <span className='name'>{item.fileName}</span>
              </Tooltip>
            </div>
          );
        },
      },
      {
        title: '创建人',
        width: '12%',
        dataIndex: 'adminName',
        render: (_value, item) => {
          return <span>{item.operatorName}</span>;
        },
      },
      {
        title: '上传时间',
        width: '20%',
        dataIndex: 'created',
        render: (_value, item) => {
          return item.failState ? '-' : <span>{moment(item.created).format('YYYY-MM-DD HH:mm')}</span>;
        },
      },
      {
        title: '大小',
        width: '12%',
        dataIndex: 'size',
        render: (_value, item) => {
          return <span>{item.fileSize}</span>;
        },
      },
      {
        title: '操作',
        width: '16%',
        dataIndex: 'control',
        render: (_value, item) => {
          const { failObject } = this.state;
          const uploadFail = failObject[item.id];

          // 上课前30分钟/上课中/已结束的情况下都不可操作
          if (this.props.data.startTime < Date.now() + 1800000 || item.progress || uploadFail) {
            return <span>-</span>;
          }
          return (
            <Popconfirm title='你确定要删除这个课件吗？' onConfirm={() => this.deleteFile(item)} onCancel={() => {}}>
              <span
                style={{
                  color: '#2966FF',
                  cursor: 'pointer',
                }}>
                删除
              </span>
            </Popconfirm>
          );
        },
      },
    ];
    const { list, scanFileModal, editData, cancelObject, showSelectFileModal, selectedFileList, diskList, showPreviewModal, previewStatus, url } = this.state;
    const _list = _.reject(list, (item) => cancelObject[item.id]);
    const { thirdPartType } = this.props.data
    return (
      <Modal
        visible={true}
        title='课件管理'
        footer={null}
        maskClosable={false}
        closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}
        className='manage-courseware-modal'
        width={_.isEmpty(_list) ? 680 : 800}
        onCancel={() => {
          this.props.onCancel();
        }}>
        {_.isEmpty(_list) ? (
          <div className='empty-body'>
            <div id='lottie-box' className='empty-image'></div>
            { thirdPartType === "WECHAT" && <div className="qiwei-tip">企微直播<br/>Mac暂不支持上传课件，Windows可在直播间添加课件</div>}
            <Button className='empty-button' type='primary' 
            disabled={thirdPartType === "WECHAT"}
            onClick={() => {
              if (thirdPartType !== "WECHAT") {
                this.addFile()
              }
            }}>
              上传课件
            </Button>
            { thirdPartType !== "WECHAT" && <p className='empty-tip'>提前上传直播需要的课件和素材，直播将会变得更便捷！</p>}
          </div>
        ) : (
          <div className='manage-body'>
            <div id='lottie-box' className='empty-image' style={{ display: 'none' }}></div>
            <div className='header'>
              <Button className='header-button' type='primary' onClick={() => this.addFile()}>
                上传课件
              </Button>
            </div>
            <XMTable
              renderEmpty={{
                image: college,
                description: '暂无数据',
              }}
              size='small'
              pagination={false}
              rowKey={(record) => record.id}
              dataSource={_list}
              columns={columns}
              bordered
            />
          </div>
        )}
        {scanFileModal && <ScanFileModal item={editData} fileType={editData.fileType} close={() => this.setState({ scanFileModal: false })} />}
        <SelectPrepareFileModal
          multiple={true}
          scene='liveCourse'
          operateType='select'
          isOpen={showSelectFileModal}
          diskList={diskList}
          selectedFileList={selectedFileList}
          onClose={() => {
            this.setState({ showSelectFileModal: false });
          }}
          onSelect={this.handleAddFile}
        />
        {showPreviewModal && <PreviewFileModal onCancel={() => this.cancelPreview()} previewStatus={previewStatus} url={url} />}
      </Modal>
    );
  }
}

export default ManageCoursewareModal;
