/*
 * @Author: 吴文洁 
 * @Date: 2020-06-22 14:26:37 
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-06-08 18:18:46
 */
import React from 'react';
import { Modal, Button, Table, message, Tooltip, Spin, Popconfirm } from 'antd';
import { QuestionCircleOutlined,LoadingOutlined} from "@ant-design/icons";
import _ from 'underscore';
import moment from 'moment';
import Lottie from "lottie-web";
import User from '@/common/js/user';
import { suffixType, DEFAULT_SIZE_UNIT } from '@/common/constants/academic/liveEnum';
import { FileVerifyMap, FileTypeIcon } from '@/common/constants/academic/lessonEnum';
import ScanFileModal from '@/modules/prepare-lesson/modal/ScanFileModal'
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Service from '@/common/js/service';
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: []
    }
  }

  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(item) {
    if (!item.srcDocUrl) return null;

    const suffix = _.last(item.fileName.split('.')).toLowerCase();
    const type = suffixType[suffix]
    const fileType = FileVerifyMap[type].type;
    
    switch (fileType) {
      case "PDF":
        window.open(item.srcDocUrl, "_blank");
        break;
      case "Excel":
      case "EXCEL":
      case "PPT":
      case "PPTX":
      case "word":
      case "WORD":
      case "DOCX":
      case "DOC":
        let size = parseFloat(item.fileSize.replace(/M$|KB$/g, ''));
        if (item.fileSize.includes('KB')) {
          size = 0;
        }
        if (((fileType == 'word' || fileType == 'PPT') && size > 10) || ((fileType == 'Excel') && size > 5)) {
          Modal.confirm({
            title: '抱歉，不能在线预览',
            content: '由于文件较大，不支持在线预览，请下载后再查看',
            icon: <QuestionCircleOutlined />,
            okText:"下载",
            onOk:() => {
              const a = document.createElement('a');
              a.href = item.srcDocUrl;
              a.click();
            }
          });
        } else {
          const scanUrl = "https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(item.srcDocUrl);
          window.open(scanUrl, "_blank");
        }
        break;
      case "JPG":
      case "PNG":
      case "MP4":
      case "MP3":
        this.setState({ scanFileModal: true, editData: { fileType, ossAddress: item.srcDocUrl } })
        break;
      default:
        break;
    }
  };


  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];

          // 上课前45分钟/上课中/已结束的情况下都不可操作
          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
    } = this.state;
    const _list = _.reject(list, (item) => cancelObject[item.id]);
    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>
              <Button
                className="empty-button"
                type="primary"
                onClick={() => this.addFile()}
              >上传课件</Button>
              <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>
            <Table
              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}
        />
      </Modal>
    )
  }
}

export default ManageCoursewareModal;