/*
 * @Author: wufan
 * @Date: 2020-04-28 18:05:30
 * @LastEditors: yuananting
 * @LastEditTime: 2021-07-15 14:04:21
 * @Description: 线上课课程课节详情
 */

import React,{useEffect, useState} from 'react';
import Breadcrumbs from "@/components/Breadcrumbs";
import { withRouter } from "react-router-dom";
import CourseService from '@/domains/course-domain/CourseService'
import underscore  from 'underscore';
import ScanFileModal from '@/modules/resource-disk/modal/ScanFileModal.jsx';
import { FileTypeIcon } from '@/common/constants/academic/lessonEnum'
import BaseService from "@/domains/basic-domain/baseService";
import {YZ_APPId,YZ_PREVIEW_URL} from '@/domains/basic-domain/constants';
import PreviewFileModal from '@/bu-components/PreviewFileModal';
import './VideoCourseDetail.less';

declare var getParameterByName: any;
declare var window: any;
const FileTypeIconMap:any = FileTypeIcon
function VideoCourseDetail(){
    const courseId =  window.getParameterByName("courseId"); // 课程ID
    const [coverUrl,setCoverUrl] = useState("");
    const [videoName,setVideoName] = useState("");
    const [scheduleVideoUrl,setScheduleVideoUrl] = useState("");
    const [courseChapterList,setCourseChapterList] = useState<Array<Object>>([]);
    const [courseName,setCourseName] = useState("");
    const [categoryName,setCategoryName] = useState("");
    const [scanFileModal,setScanFileModal] = useState<any>(null);
    const [showPreviewModal,setShowPreviewModal] = useState(false); //是否显示loading
    // const [previewing,setPreviewing] = useState(false); //是否正在预览
    const [previewStatus,setPreviewStatus] = useState('UPLOAD'); //预览文件的生成状态 
    const [url,setUrl] =  useState('');
    let previewing = false;
    useEffect(()=>{
        handleFetchScheudleDetail(courseId);
    },[courseId])


      // 获取线上课详情
    function  handleFetchScheudleDetail(courseId: string){
    CourseService.videoScheduleDetail({
      courseId
    }).then((res) => {
      const { result = {} } = res || {}
      const { courseName, courseMediaVOS, categoryName, courseChapterVOList =[] } = result
      let coverId:string = "";
      let coverUrl: string = "";
      let videoType: string = "";
      let videoDuration: number = 0;
      let videoName: string = "";
      let scheduleVideoUrl: string = "";

      courseMediaVOS.map((item:any) => {
        switch (item.contentType) {
          case 'COVER':
            coverId = item.mediaContent
            coverUrl = item.mediaUrl
            break
          case 'SCHEDULE':
            videoDuration = item.videoDuration
            videoName = item.mediaName
            scheduleVideoUrl = item.mediaUrl
            videoType = item.mediaType
            break
          default:
            break
        }
        return item
      })

      setCoverUrl(coverUrl);
      setVideoName(videoName);
      setScheduleVideoUrl(scheduleVideoUrl);
      setCourseName(courseName);
      setCategoryName(categoryName);
      setCourseChapterList(courseChapterVOList);
    })
  }
  async function handleScanFileModal(fileType: string = "MP4", fileObj:any){
    const {fileVersionId,name,mediaUrl,id} = fileObj;
    if(fileType === "VIDEO"){
      const scanFileModal = (
        <ScanFileModal
          fileType={fileType}
          item={fileObj}
          close={() => {
            setScanFileModal(null);
          }}
        />
      );
      setScanFileModal(scanFileModal)
    }else{
      if(!fileVersionId){
        setShowPreviewModal(true);
        previewing = true;
        setPreviewStatus('UPLOAD');
        const uploadParams ={
          fileUrl:mediaUrl,
          yoZoTypeEnum:'UPLOAD'
        }
        const uploadSign:any = await BaseService.getYoZoSign(uploadParams);
        BaseService.yoZoUpload(mediaUrl,YZ_APPId,uploadSign).then(async function (response){
          const saveParams ={ 
            fileVersionId:response.data.data.fileVersionId,
            courseChapterId:id
          }
          BaseService.saveFileVersionIdByCourseChapter(saveParams);
          if(previewing){
            const  previewParams ={
              fileVersionId:response.data.data.fileVersionId,
              yoZoTypeEnum:'VIEW',
              htmlTitle:name
            }
            const previewSign = await BaseService.getYoZoSign(previewParams);
            const url = `${YZ_PREVIEW_URL}?fileVersionId=${response.data.data.fileVersionId}&appId=${YZ_APPId}&sign=${previewSign}&htmlTitle=${name}`
            setPreviewStatus('UPLOAD_SUCCESS');
            setUrl(url)
          }
        })
      }else{
        const  previewParams ={
          fileVersionId,
          yoZoTypeEnum:'VIEW',
          htmlTitle:name
        }
        const previewSign = await BaseService.getYoZoSign(previewParams);
        const url = `${YZ_PREVIEW_URL}?fileVersionId=${fileVersionId}&appId=${YZ_APPId}&sign=${previewSign}&htmlTitle=${name}`
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('href', url);
        a.setAttribute('target', '_blank');
        a.click();
        document.body.removeChild(a)
      }
    }
  }
  
  // function  previewingSet(){
  //   return new Promise(async (resolve) => {
  //     setShowPreviewModal(true);
  //     setPreviewing(true);
  //     setPreviewStatus('UPLOAD');
  //     resolve(true);
  //   })
  // }
  function cancelPreview(){
    setShowPreviewModal(false);
    // setPreviewing(false);
    previewing = false;
    setPreviewStatus('UPLOAD');
  }


    return <div className="page video-course-detail">
                <Breadcrumbs
                    navList="课程详情"
                    goBack={() => {
                        window.RCHistory.goBack();
                    }}
                />

            <div className="box">
                <div className="course-detail">
                    <div className='course-detail__img'>
                        {/* 如果视频和封面都没有上传的话, 那么就显示缺省, 如果上传了视频, 那么封面图就默认显示视频的第一帧, 如果上传了封面图, 那么就显示上传的封面图 */}
                        <img src={coverUrl || `https://image.xiaomaiketang.com/xm/TwtGPQGE4K.png`} alt='' />
                    </div>
                    <div className="course-detail__info">
                        <div className="info__title">{courseName}</div>
                        <div className="info__category">{`课程分类：${categoryName}`}</div>
                        <div className="info__chapterNum">{`课节数量：${courseChapterList.length}`}</div>
                    </div>
                </div>

                <div className="course-chapter">
                    <div className="course-chapter__total">{`共${courseChapterList.length}个课节`}</div>
                    <div className="course-chapter__list">
                        <If condition={courseChapterList.length > 0}>
                            {
                                underscore.map(courseChapterList,(item: any,index: number) => {
                                return <div className='course-ware' onClick={()=>{handleScanFileModal(item.mediaType,item)}} key={index}>
                                        <div className="course-ware__index">{index < 9 ? `0${index + 1 } ` : index + 1}</div>
                                        <img className='course-ware__img' src={FileTypeIconMap[item.mediaType]} alt='' />
                                        <div className='course-ware__name'>{item.name}</div>
                                </div>
                                })
                            }
                        </If>
                    </div>
                </div>
            </div>
            { showPreviewModal &&
             <PreviewFileModal onCancel={()=>cancelPreview()} previewStatus={previewStatus} url={url}/>
            }
            {scanFileModal}
    </div>
}

export default withRouter(VideoCourseDetail);