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

import React from 'react';
import { Button, Input, Radio, message, Modal,Cascader} 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 AddVideoIntro from './components/AddVideoIntro';
import SelectStudent from '../modal/select-student';
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal';
import PreviewCourseModal from '../modal/PreviewCourseModal';
import StoreService from "@/domains/store-domain/storeService";
import CourseService from "@/domains/course-domain/CourseService";
import User from '@/common/js/user';
import _ from "underscore";
import './AddGraphicsCourse.less';

const EDIT_BOX_KEY = Math.random();
const fieldNames  = { label: 'categoryName', value: 'id', children: 'sonCategoryList' };

//添加课程时课程默认的一些值
const defaultShelfState = 'YES';
const defaultScheduleMedia = [{          
  contentType:'INTRO',
  mediaType: 'TEXT',
  mediaContent: '',
  key: EDIT_BOX_KEY
}]
const whetherVisitorsJoin = 'NO'


class AddGraphicsCourse 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,           // 需要被截取的图片
      courseName: null,        // 图文课名称
      scheduleVideoId: null,     // 图文课链接
      coverId: null,             // 图文封面的recourceId
      coverUrl: 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png',            // 图文课封面
      studentList: [],           // 上课学员列表
      shelfState:'YES',          //是否开启店铺展示
      scheduleMedia: [{          // 图文课媒体资源
        contentType:"INTRO",
        mediaType: 'TEXT',
        mediaContent: '',
        key: EDIT_BOX_KEY
      }],
      diskList: [],              // 机构可见磁盘目录
      selectedFileList: [],      // 已经从资料云盘中勾选的文件
      showCutModal: false,       // 是否显示截图弹窗
      showSelectFileModal: false,
      studentModal: false,
      categoryName:null, //分类名称
      courseCatalogList:[], //分类列表
      categoryId:null, //分类的Id值
      whetherVisitorsJoin:'NO' // 是否允许游客加入
    }
  }

  componentWillMount() {
    // this.handleFetchDiskList();
    const { id, pageType } = this.state;
    this.getCourseCatalogList();
    if (pageType === 'edit') {
      this.handleFetchScheudleDetail(id);
      // this.handleFetchStudentList(id);
    }
  }
  //获取分类列表
  getCourseCatalogList = ()=>{
    StoreService.getCourseCatalogList({current:1,size:1000}).then((res) => {
        this.setState({
          courseCatalogList:res.result.records
        })
    });
  }
  
  catalogChange= (value) => {
    const changeValueLength = value.length;
    switch (changeValueLength){
      case 1:
        this.setState({categoryId:value[0]});   
      break;
      case 2:
        this.setState({categoryId:value[1]});
      break;
      default:
        this.setState({categoryId:null});
      break;    
    }
  }
  // 获取图文课详情
  handleFetchScheudleDetail = (courseId) => {
    CourseService.videoScheduleDetail({
      courseId
    }).then((res) => {
      const { result = {} } = res || {};
      const {
        // coverId,
        // coverUrl,
        // videoType,
        // videoDuration,
        // videoName,
        // scheduleMedia,
        courseName,
        // scheduleVideoId,
        // scheduleVideoUrl,
        shelfState,
        whetherVisitorsJoin,
        courseMediaVOS,
        categoryOneName,
        categoryTwoName,
        categoryId
      } = result;
        let coverId;
        let coverUrl;
        let videoType;
        let videoDuration;
        let videoName;
        let scheduleMedia = [];
        let scheduleVideoId;
        let scheduleVideoUrl;
        
        courseMediaVOS.map((item) => {
          switch (item.contentType){
            case "COVER":
              coverId = item.mediaContent;
              coverUrl = item.mediaUrl;
            break;
            case "SCHEDULE":
              videoDuration = item.videoDuration;
              videoName = item.mediaName;
              scheduleVideoId = item.mediaContent;
              scheduleVideoUrl = item.mediaUrl;
              videoType = item.mediaType;
            break;
            case "INTRO":
              scheduleMedia = [...scheduleMedia,item]
            break;  
            default:
            break;
          }
          return item;
        })
      
      let  categoryName;
      if( categoryTwoName ){
        categoryName = `${categoryOneName}-${categoryTwoName}`;
      }else{
        categoryName = `${categoryOneName}`;
      }
      this.setState({
        coverId,
        coverUrl,
        videoType,
        videoName,
        videoDuration,
        scheduleMedia,
        courseName,
        scheduleVideoId,
        scheduleVideoUrl,
        shelfState,
        whetherVisitorsJoin,
        categoryName,
        categoryId
      });
    })
  }


  handleGoBack = () => {
    const {
      coverId,
      videoName,
      videoDuration,
      courseName,
      scheduleMedia, 
      scheduleVideoId,
      categoryId,
      shelfState,
      whetherVisitorsJoin
    } = this.state;
    if(videoName || videoDuration || scheduleVideoId  || !_.isEqual(scheduleMedia, defaultScheduleMedia) || categoryId || courseName || coverId ||  shelfState !== defaultShelfState || whetherVisitorsJoin !== whetherVisitorsJoin ){
      Modal.confirm({
        title: '确认要返回吗?',
        content: '返回后，本次编辑的内容将不被保存。',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        onOk: () => {
          RCHistory.goBack();
        }
      });
    }else{
      RCHistory.goBack();
    }
  }

  // 修改表单
  handleChangeForm = (field, value, coverUrl) => {
    console.log('field',value);
    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,
      courseName,
      scheduleMedia,
      videoDuration

    } = this.state;

    const courseBasinInfo = {
      coverUrl,
      scheduleVideoUrl,
      courseName,
      videoDuration
    }
    const courseIntroInfo = {
      liveCourseMediaRequests: scheduleMedia
    }

    const previewCourseModal = (
      <PreviewCourseModal
        type="videoCourse"
        courseBasicInfo={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,
      courseName,
      scheduleMedia, 
      scheduleVideoId,
      scheduleVideoUrl,
      categoryId,
      shelfState,
      whetherVisitorsJoin
    } = this.state;

    const commonParams = {
      videoName,
      videoDuration, 
      scheduleVideoId,
      scheduleMedia: scheduleMedia.filter(item => !!item.mediaContent),
      categoryId,
      courseName,
      coverId,
      operatorId:User.getStoreUserId(),
      storeId:User.getStoreId(),
      shelfState,
      whetherVisitorsJoin
    };
    // 校验必填字段:课程名称, 课程图文
    this.handleValidate(courseName, scheduleVideoId,categoryId, scheduleMedia).then((res) => {
      if (!res) return;
      if (pageType === 'add') {
        CourseService.createVideoSchedule(commonParams).then((res) => {
          if (!res) return;
          message.success("新建成功");
          window.RCHistory.goBack();
        })
      } else {
        const editParams = {
          courseId:id,
          ...commonParams,
        }
        CourseService.editVideoSchedule(editParams).then((res) => {
          if (!res) return;
          message.success("保存成功");
          window.RCHistory.goBack();
        });
      }
    });
  }

  handleValidate = (courseName, scheduleVideoId,categoryId,scheduleMedia) => {
    return new Promise((resolve) => {
      if (!courseName) {
        message.warning('请输入课程名称');
        resolve(false);
        return false
      }  
      if (!scheduleVideoId) {
        message.warning('请上传图文');
        resolve(false);
        return false
      }  
      if(!categoryId){
        message.warning('请选择课程分类');
        resolve(false);
        return false
      }
      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);
          return false
        }
      }
      resolve(true);
    });
  }

  render() {
    const {
      pageType,courseName, scheduleVideoId, coverId,
      coverUrl, scheduleVideoUrl, studentList, scheduleMedia,
      showCutModal, showSelectFileModal, diskList,
      imageFile, joinType, videoName, videoType,shelfState,
      categoryName,courseCatalogList,whetherVisitorsJoin 
    } = 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={courseName}
                placeholder="请输入图文课的名称（40字以内）"
                maxLength={40}
                style={{ width: 240 }}
                onChange={(e) => { this.handleChangeForm('courseName', e.target.value)}}
              />
            </div>

            <div className="cover-url flex mt16">
              <div className="label">封面图：</div>
              <div className="cover-url__wrap">
                <div className="img-content">
                  <img src={coverUrl} />
                </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="course-catalog required">
              <span className="label">课程分类：</span>
              { (pageType === 'add') && 
                <Cascader defaultValue={[categoryName]} options={courseCatalogList} displayRender={	label => label.join('-')}  fieldNames={fieldNames} onChange={this.catalogChange} style={{ width: 240 }} placeholder="请选择课程分类"  suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}/>
              }
              { (pageType === 'edit' && categoryName ) && 
                <Cascader defaultValue={[categoryName]} options={courseCatalogList} displayRender={	label => label.join('-')}  fieldNames={fieldNames} onChange={this.catalogChange} style={{ width: 240 }} placeholder="请选择课程分类" suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}/>
              }
            </div>
            <div className="intro-info mt16">
              <AddVideoIntro
                data={{
                  liveCourseMediaRequests: scheduleMedia,
                  shelfState,
                  whetherVisitorsJoin,
                  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>
        
        {/* 选择备课文件弹窗 */}
        { showSelectFileModal &&
          <SelectPrepareFileModal
            operateType="select"
            selectTypeList={['MP4']}
            accept="video/mp4"
            confirm={{
              title: '文件过大，无法上传',
              content: '为保障学员的观看体验，上传的图文大小不能超过2G',
            }}
            tooltip={'格式支持mp4，大小不超过2G'}
            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() }}
        />
        { this.state.previewCourseModal }
      </div>
    )
  }
}

export default AddGraphicsCourse;
