/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:07:47
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2020-12-25 15:26:06
 * @Description: 视频课新增/编辑页
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react';
import { Button, Input, Radio, message, Modal } from 'antd';

import { DISK_MAP, FileTypeIcon, FileVerifyMap } from '@/common/constants/academic/lessonEnum';
import { ImgCutModalNew } from '@/components';
import ShowTips from "@/components/ShowTips";
import Breadcrumbs from "@/components/Breadcrumbs";

import AddLiveIntro from '../components/AddLiveIntro';
import SelectStudent from '../modal/select-student';
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal';
import PreviewCourseModal from '../modal/PreviewCourseModal';

import './AddVideoCourse.less';

const EDIT_BOX_KEY = Math.random(16);
class AddVideoCourse extends React.Component {

  constructor(props) {
    super(props);

    const id = getParameterByName("id");
    const pageType = getParameterByName("type");

    this.state = {
      id,                        // 视频课ID,编辑的时候从URL上带过来
      pageType,                  // 页面类型: add->新建 edit->编辑
      imageFile: null,           // 需要被截取的图片
      
      scheduleName: null,        // 视频课名称
      scheduleVideoId: null,     // 视频课链接
      coverId: null,             // 视频封面的recourceId
      coverUrl: null,            // 视频课封面
      joinType: null,            // 观看模式, 默认为指定某些学员可以观看
      studentList: [],           // 上课学员列表
      scheduleMedia: [{          // 视频课媒体资源
        mediaType: 'TEXT',
        mediaContent: '',
        key: EDIT_BOX_KEY
      }],

      diskList: [],              // 机构可见磁盘目录
      selectedFileList: [],      // 已经从资料云盘中勾选的文件
      showCutModal: false,       // 是否显示截图弹窗
      showSelectFileModal: false,
      studentModal: false,
    }
  }

  componentWillMount() {
    // this.handleFetchDiskList();

    const { id, pageType } = this.state;
    if (pageType === 'edit') {
      this.handleFetchScheudleDetail(id);
      this.handleFetchStudentList(id);
    }
  }

  // 获取视频课详情
  handleFetchScheudleDetail = (scheduleId) => {
    window.axios.Apollo('public/apollo/getLessonScheduleDetail', {
      scheduleId
    }).then((res) => {
      const { result = {} } = res || {};
      const {
        coverId,
        coverUrl,
        videoType,
        videoDuration,
        videoName,
        studentIds,
        scheduleMedia,
        scheduleName,
        scheduleVideoId,
        joinType,
        scheduleVideoUrl,
      } = result;

    
      this.setState({
        coverId,
        coverUrl,
        videoType,
        videoName,
        videoDuration,
        studentIds,
        scheduleMedia,
        scheduleName,
        scheduleVideoId,
        joinType,
        scheduleVideoUrl,
      });

    })
  }

  // 获取视频课学员
  handleFetchStudentList = (scheduleId) => {
    window.axios.Apollo('public/apollo/getLessonStuIdListByScheduleId', {
      scheduleId
    }).then((res) => {
      const studentIds = res.result || [];
      const studentList = [];
      _.each(studentIds, (item) => {
        studentList.push({ studentId: item });
      });

      this.setState({ studentList })
    });
  }

  // 获取机构可见的磁盘
  // handleFetchDiskList = () => {
  //   axios.Apollo('public/apollo/getUserDisk', {}).then((res) => {
  //     const { result = [] } = res;
  //     const diskList = result.map((item) => {
  //       return {
  //         ...item,
  //         folderName: DISK_MAP[item.disk]
  //       }
  //     });
  //     this.setState({ diskList });
  //   });
  // }

  handleGoBack = () => {
    Modal.confirm({
      title: '确认要返回吗?',
      content: '返回后，本次编辑的内容将不被保存。',
      okText: '确认返回',
      cancelText: '留在本页',
      icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
      onOk: () => {
        RCHistory.goBack();
      }
    });
  }

  // 修改表单
  handleChangeForm = (field, value, coverUrl) => {
    this.setState({
      [field]: value,
      coverUrl: coverUrl ? coverUrl : this.state.coverUrl
    });
  }
  
  // 显示选择学员弹窗
  handleShowSelectStuModal = () => {
    this.setState({ studentModal : true });

    const { studentList, selectedStuList } = this.state;
    // const _studentList = _.map(studentList, (item) => { 
    //   return item.studentId
    // })
    const studentModal = (
      <SelectStudent
        showTabs={true}
        type="videoCourse"
        onSelect={this.handleSelectStudent}
        after={true} //表明是不是上课后的状态
        studentList={studentList}
        close={() => {
          this.setState({
            studentModal: null,
          });
        }}
      />
    )
    this.setState({ studentModal });
  }

  handleSelectStudent = (studentIds) => {
    let studentList = [];
    _.each(studentIds, (item) => {
      studentList.push({ studentId: item });
    });

    // this.setState({ studentModal: null });
    this.setState({ studentList  });
    this.setState({ studentModal : false });
  }
  
  // 显示预览弹窗
  handleShowPreviewModal = () => {
    const {
      coverUrl,
      scheduleVideoUrl,
      scheduleName,
      scheduleMedia
    } = this.state;

    const courseBasinInfo = {
      coverUrl,
      scheduleVideoUrl,
      courseName: scheduleName,
    }

    const courseIntroInfo = {
      liveCourseMediaRequests: scheduleMedia
    }

    const previewCourseModal = (
      <PreviewCourseModal
        type="videoCourse"
        courseBasinInfo={courseBasinInfo}
        courseIntroInfo={courseIntroInfo}
        close={() => {
          this.setState({
            previewCourseModal: null
          })
        }}
      />
    );

    this.setState({ previewCourseModal });
  }
  
  // 选择视频
  handleSelectVideo = (file) => {
    this.setState({
      showSelectFileModal: false
    })
    const { ossUrl, resourceId, folderName, folderFormat, folderSize } = file;

    const videoDom = document.createElement('video');
    videoDom.src = ossUrl;
    videoDom.onloadedmetadata = () => {
      this.setState({
        size: folderSize,
        videoName: folderName,
        videoType: folderFormat,
        scheduleVideoUrl: ossUrl,
        scheduleVideoId : resourceId,
        videoDuration: videoDom.duration
      });
    }
  }

  // 上传封面图
  handleShowImgCutModal = (event) => {
    const imageFile = event.target.files[0];
    if (!imageFile) return;
    this.setState({
      imageFile,
      showCutModal: true,
    });
  }
  // 保存
  handleSubmit = () => {
    const { instId, adminId } = window.currentUserInstInfo;
    
    const {
      id,
      size,
      coverId,
      coverUrl,
      pageType,
      joinType,
      videoName,
      videoDuration,
      studentList,
      scheduleName,
      scheduleMedia, 
      scheduleVideoId,
      scheduleVideoUrl,
    } = this.state;

    const commonParams = {
      size,
      instId,
      coverId,
      videoName,
      videoDuration,
      scheduleName,
      scheduleVideoId,
      joinType,
      teacherId: adminId,
      studentIds: _.pluck(studentList, "studentId"),
      scheduleMedia: scheduleMedia.filter(item => !!item.mediaContent),
    };
    // 校验必填字段:课程名称, 课程视频
    this.handleValidate(scheduleName, scheduleVideoId, joinType, scheduleMedia).then((res) => {
      if (!res) return;
      if (pageType === 'add') {
        window.axios.Apollo('public/apollo/createLessonSchedule', commonParams).then((res) => {
          if (!res) return;
          message.success("新建成功");
          // localStorage.setItem('videoCourseItem', JSON.stringify({
          //   ...commonParams,
          //   coverUrl,
          //   scheduleVideoUrl,
          //   id: res.result
          // }));

          window.RCHistory.goBack();
        })
      } else {
        const editParams = {
          id,
          ...commonParams,
        }
        window.axios.Apollo('public/apollo/editLessonSchedule', editParams).then((res) => {
          if (!res) return;
          message.success("保存成功");
          window.RCHistory.goBack();
        });
      }
    });
  }

  handleValidate = (scheduleName, scheduleVideoId, joinType, scheduleMedia) => {
    return new Promise((resolve) => {
      if (!scheduleName) {
        message.warning('请输入课程名称');
        resolve(false);
      } else if (!scheduleVideoId) {
        message.warning('请上传视频');
        resolve(false);
      } else if (!joinType) {
        message.warning('请选择观看设置');
        resolve(false);
      } else {
        const textMedia = scheduleMedia.filter((item) => item.mediaType === 'TEXT');
        for (let i = 0, len = textMedia.length; i < len; i++) {
          if (textMedia[i].mediaContentLength && textMedia[i].mediaContentLength.length > 1000) {
            message.warning(`第${i+1}个文字简介的字数超过了1000个字`);
            resolve(false);
          }
        }
      }
      resolve(true);
    });
  }

  render() {
    const {
      pageType, scheduleName, scheduleVideoId, coverId,
      coverUrl, scheduleVideoUrl, studentList, scheduleMedia,
      showCutModal, showSelectFileModal, diskList,
      imageFile, joinType, videoName, videoType ,studentModal
    } = this.state;

    // 已选择的上课学员数量
    const hasSelectedStu = studentList.length;

    const courseWareIcon = FileVerifyMap[videoType] ? FileTypeIcon[FileVerifyMap[videoType].type] : FileTypeIcon[videoType];
    
    return (
      <div className="page add-video-course-page">
        <Breadcrumbs
          navList={pageType === "add" ? "新建视频课" : "编辑视频课"}
          goBack={this.handleGoBack}
        />

        <div className="box">
          <div className="show-tips">
            <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦助教保有依据国家规定及平台规则进行处理的权利" />
          </div>

          <div className="form">
            <div className="course-name required">
              <span className="label">课程名称：</span>
              <Input
                value={scheduleName}
                placeholder="请输入视频课的名称（40字以内）"
                maxLength={40}
                style={{ width: 240 }}
                onChange={(e) => { this.handleChangeForm('scheduleName', e.target.value)}}
              />
            </div>

            <div className="upload-video mt16">
              <div className="content flex">
                <span className="label required">视频上传：</span>
                <div className="value">
                  {
                    scheduleVideoId ?
                    <div className="course-ware">
                      <img  className="course-ware__img" src={courseWareIcon} />
                      <span className="course-ware__name">{videoName}</span>
                    </div> :
                    <div className="course-ware--empty">从资料云盘中选择视频</div>
                  }
                  
                </div>
              </div>
              <div className="sub-content">
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      showSelectFileModal: true
                    })
                  }}
                >{`${(pageType === 'add' && !scheduleVideoId) ? '选择' : '更换'}视频`}</Button>

                <span className="tips">视频数量限制1个，大小不超过500M</span>
              </div>
            </div>

            <div className="cover-url flex mt16">
              <div className="label">视频封面：</div>
              <div className="cover-url__wrap">
                <div className="img-content">
                  {/* 如果视频和封面都没有上传的话, 那么就显示缺省, 如果上传了视频, 那么封面图就默认显示视频的第一帧, 如果上传了封面图, 那么就显示上传的封面图 */}
                  {
                    (scheduleVideoUrl || coverUrl )?
                    <img src={coverUrl || `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast`} /> :
                    <div className="empty-img">若不上传<br />系统默认将视频首帧作为封面图</div>
                  }
                </div>
                <div className="opt-btns">
                  <input
                    type="file"
                    accept="image/png, image/jpeg, image/jpg"
                    ref="picInputFile"
                    style={{display: 'none'}}
                    onChange={(event) => { this.handleShowImgCutModal(event) }}
                  />

                  <Button onClick={() => {
                    this.setState({
                      currentInputFile: this.refs.picInputFile
                    });
                    this.refs.picInputFile.click()
                  }}>{`${(pageType === 'add' && (!scheduleVideoId && !coverUrl)) ? '上传' : '修改'}封面`}</Button>
                  <div className="tips">建议尺寸1280*720px或16:9。封面图最大5M，支持jpg、jpeg和png。</div>
                </div>
              </div>
            </div>

            <div className="watch-setting flex mt16">
              <div className="label required">分享设置：</div>
              <div className="content">
                <Radio.Group
                  onChange={(e) => this.handleChangeForm('joinType', e.target.value)}
                  value={joinType}
                >
                  <Radio value={'ALL'}>
                    <div className="radio-item">
                      <div className="text mr16">允许任何学员通过视频课链接加入学习</div>
                      <div className="sub-text">加入后，在读学员可通过家长端和视频课链接观看，非在读学员仅可通过视频课链接观看</div>
                    </div>
                  </Radio>

                  <Radio value={'NORMAL'}>
                    <div className="radio-item">
                      <div className="text mr16">仅在读学员可通过视频课链接加入学习</div>
                      <div className="sub-text">加入后，在读学员可通过家长端和视频课链接观看</div>
                    </div>
                  </Radio>

                  <Radio value={'ASSIGN'}>
                    <div className="radio-item mb0">
                      <div className="text mr16">仅指定学员可通过视频课链接加入学习</div>
                      <div className="sub-text">加入后，在读学员可通过家长端和视频课链接观看，非在读学员仅可通过视频课链接观看</div>
                    </div>
                  </Radio>
                </Radio.Group>

                {
                  // 当观看模式为指定学员时,显示选择学员的入口
                  joinType === 'ASSIGN' &&
                  <div className="select-student flex">
                    <Button onClick={this.handleShowSelectStuModal}>选择学员</Button>
                    <div className="has-selected">
                      已选择 <span style={{ color: "#FF8534" }}>{hasSelectedStu}</span> 名学员
                    </div>
                  </div>
                }
              </div>
            </div>
            <div className="intro-info mt16">
              <AddLiveIntro
                data={{
                  liveCourseMediaRequests: scheduleMedia,
                  label: '视频课简介'
                }}
                onChange={this.handleChangeForm}
              />
            </div>
          </div>
        </div>

        <div className="footer">
          <Button onClick={this.handleGoBack}>取消</Button>
          <Button onClick={this.handleShowPreviewModal}>预览</Button>
          <Button type="primary" onClick={_.debounce(() => this.handleSubmit(), 3000, true)}>保存</Button>
        </div>
        
        {/* 选择备课文件弹窗 */}
        <SelectPrepareFileModal
          operateType="select"
          selectTypeList={['MP4']}
          accept="video/mp4"
          confirm={{
            title: '文件过大，无法上传',
            content: '为保障学员的观看体验，上传的视频大小不能超过500M',
          }}
          tooltip={'格式支持mp4，大小不超过500M'}
          isOpen={showSelectFileModal}
          diskList={diskList}
          addVideo={true}
          onClose={() => {
            this.setState({ showSelectFileModal: false })
          }}
          onSelect={this.handleSelectVideo}
        />
        
        <ImgCutModalNew
          title="裁剪"
          width={550}
          cutWidth={500}
          cutHeight={282}
          cutContentWidth={500}
          cutContentHeight={300}
          visible={showCutModal}
          imageFile={imageFile}
          bizCode='LIVE_COURSE_MEDIA'
          onOk={(urlStr, resourceId) => {
            this.setState({ showCutModal: false });
            this.handleChangeForm('coverId', resourceId, urlStr)
            this.state.currentInputFile.value = '';
          }}
          onClose={() => this.setState({ showCutModal: false })}
          reUpload={() => { this.state.currentInputFile.click() }}
        />
        {/* {
          <SelectStudent
            addVideo={'addVideo'}
            studentModal={studentModal}
            showTabs={true}
            type="videoCourse"
            onSelect={this.handleSelectStudent}
            after={true} //表明是不是上课后的状态
            savedList={studentList}
            close={() => {
              this.setState({
                // studentModal: null,
                studentModal: false,
              });
            }}
          />
        } */}
        { this.state.studentModal }
        { this.state.previewCourseModal }
      </div>
    )
  }
}

export default AddVideoCourse;
