/*
 * @Author: 吴文洁 
 * @Date: 2020-06-22 14:26:37 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-23 09:33:02
 */
import React, { useEffect, useState } from 'react';
import { Modal, Button, Table, Progress, message, Tooltip, Spin, Popconfirm } from 'antd';
import { QuestionCircleOutlined,LoadingOutlined} from "@ant-design/icons";
import _ from 'underscore';
import moment from 'moment';
// import User from '@/core/user';
import User from '@/common/js/user';
import { suffixType, DEFAULT_SIZE_UNIT, SupportFileType } from '@/common/constants/academic/liveEnum';
import { FileVerifyMap, FileTypeIcon, DISK_MAP } 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();
    // this.handleFetchDiskList();
    // if (teacherId) {
    //   this.judgeLessonPermisson();
    // }
  }

  // 判断资料云盘权限
  // judgeLessonPermisson = () => {
  //   const query = {
  //     permissionCode: "2001"
  //   };
  //   axios.Apollo("public/apollo/judgeLessonPermission", query).then(res => {
  //     this.setState({ isLessonPermission: res.result })
  //   });
  // };
  
  // 获取课件列表
  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 });
    })
  }

  // 获取机构可见的磁盘目录
  // handleFetchDiskList = () => {
  //   Service.Hades('public/apollo/getUserDisk', {}).then((res) => {
  //     const { result = [] } = res;
  //     const diskList = result.map((item) => {
  //       return {
  //         ...item,
  //         folderName: DISK_MAP[item.disk]
  //       }
  //     });
  //     this.setState({
  //       diskList,
  //     });
  //   });
  // }
  
  // 上传文件
  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;
    }
  };

  // 校验余额
  // handleCheckBalance = async () => {
  //   const { type } = this.props;
  //   const balanceRes = await axios.Business("public/liveAssets/query", {  });
  //   // 判断是否欠费，旗舰版用户不需要校验余额
  //   const ultimateRes = await axios.Business('public/inst/checkInstProduct', {
  //     productCodeList: ['ULTIMATESELL', 'PIP_TO_ULTIMATE', 'HIGH_TO_ULTIMATE']
  //   });

  //   const { result } = balanceRes;
  //   // balance小于0表示已经欠费
  //   if ((!result || result.balance <= 0) && !ultimateRes.result && type === 'interactive') {
  //     Modal.info({
  //       title: '无法继续操作',
  //       content: '直播服务已升级，请联系运营老师。',
  //       icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>
  //     })
  //     return false;
  //   }
  //   return true;
  // };

  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)}>
            {(type === 'JPG' || type === 'PNG') && item.progress ?
              <Spin indicator={antIcon} />
              :<img  
                src={FileTypeIcon[FileVerifyMap[fileType].type] || (item.docUrls[0] || {}).conversionFileUrl}
                alt=""
                className="item-img"
              />
            }
            <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 { uploadObject, failObject, cancelObject } = 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: '#5289FA',
                cursor: 'pointer'
              }}>删除</span>
            </Popconfirm>
          )
        },
      },
    ]
    const {
      list, scanFileModal, editData, cancelObject,
      showSelectFileModal, selectedFileList,
      diskList, currentRootDisk, isLessonPermission
    } = this.state;
    const _list = _.reject(list, (item) => cancelObject[item.id]);
    return (
      <Modal
        visible={true}
        title="课件管理"
        footer={null}
        maskClosable={false}
        className="manage-courseware-modal"
        width={_.isEmpty(_list) ? 680 : 800}
        onCancel={() => {
          this.props.onCancel()
        }}
      >
        {_.isEmpty(_list) ? 
          <div className="empty-body">
            <img  className="empty-image" src="https://image.xiaomaiketang.com/xm/s8xkAPCDex.png" alt="" />
              <Button
                className="empty-button"
                type="primary"
                onClick={() => this.addFile()}
              >上传课件</Button>
            <p className="empty-tip">提前上传直播需要的课件和素材，直播将会变得更便捷！</p>
          </div>
          : <div className="manage-body">
            <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;