/*
 * @Author: 吴文洁 
 * @Date: 2020-07-17 15:49:11 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-23 22:02:49
 * @Description: 大班互动-添加/编辑直播课
 */

import React from 'react';
import { withRouter } from "react-router-dom";
import { Button, message, Modal } from 'antd';

import ShowTips from "@/components/ShowTips";
import Breadcrumbs from "@/components/Breadcrumbs";

import AddLiveBasic from './components/AddLiveBasic';
import AddLiveClass from './components/AddLiveClass';
import AddLiveIntro from './components/AddLiveIntro';
import PreviewCourseModal from './modal/PreviewCourseModal';
import CourseService from "@/domains/course-domain/CourseService";
import moment from 'moment';
import User from '@/common/js/user';
import _ from "underscore";
import './AddLive.less';

const defaultCover = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';
const defaultBasicInfo = {
  courseName: null,  // 课程名称
  coverUrl: defaultCover,
  coverId:null,
  categoryId:null,
  categoryName:null,
};

const defaultClassInfo = {
  teacherId: null, //讲师的Id
  assistant:[], //助教
  teacherName: null,
  liveDate: null,
  timeHorizonStart: null,
  timeHorizonEnd: null,
  calendarTime: [],
  startTime: new Date().getTime() + 300000,
  endTime: new Date().getTime() + 300000,
};

const defaultIntroInfo = {
  needRecord: 'YES',
  whetherVisitorsJoin:'NO',
  liveCourseWarmMedia: {},
  // 讲师简介
  liveCourseMediaRequests: [{
    contentType:"INTRO",
    mediaType: 'TEXT',
    mediaContent: '',
    key: Math.random()
  }], 
}

class AddLive extends React.Component {
  constructor(props) {
    super(props);
    const id = getParameterByName("id");
    const type = getParameterByName("type");
    this.state = {
      id,
      type,
      loading: false,
      isEdit: true,
      courseState:'UN_START',
      // 直播课基本信息
      addLiveBasicInfo: {
        courseName: null,  // 课程名称
        coverUrl: defaultCover,
        coverId:null,
        categoryId:null,
        categoryName:null,
      },

      // 直播课上课信息
      addLiveClassInfo: {
        teacherId: null,
        teacherName: null,
        assistant:[],
        assistantStoreUserId:[],
        assistantNames:[],
        liveDate: null,
        timeHorizonStart: null,
        timeHorizonEnd: null,
        calendarTime: [], // 批量排课
        startTime: new Date().getTime() + 300000, // 批量开始时分
        endTime: new Date().getTime() + 300000 // 批量结束时分
      },

      // 直播课简介
      addLiveIntroInfo: {
        needRecord: 'YES',
        whetherVisitorsJoin:'NO',
        liveCourseWarmMedia: {},
        liveCourseMediaRequests: [{
          contentType:"INTRO",
          mediaType: 'TEXT',
          mediaContent: '',
          key: Math.random()
        }]
      },
    }
  }

  componentDidMount() {
    const { type } = this.state;
    if (type === 'edit') {
      this.getCourseDetail(); 
    } 
  }

  getCourseDetail = () => {
    let { isEdit } = this.state;
    this.setState({ loading: true });
       CourseService.getLiveCloudCourseDetail({
        liveCourseId: this.state.id
      }).then((res) => {
        const {
          teacherId,
          teacherName,
          courseName,
          startTime,
          endTime,
          courseMediaVOS,
          nickname,
          needRecord,
          whetherVisitorsJoin,
          warmMedia,
          categoryId,
          categoryName,
          admins,
          courseState
        } = res.result;
        let coverId;
        let coverUrl;
        let liveCourseMediaRequests = [];
        let liveCourseWarmMedia;
        courseMediaVOS.map((item) => {
          switch (item.contentType){
            case "COVER":
              coverId = item.mediaContent;
              coverUrl = item.mediaUrl;
            break;
            case "WARMUP":
              liveCourseWarmMedia = item;
            break;
            case "INTRO":
              liveCourseMediaRequests = [...liveCourseMediaRequests,item]
            break;  
            default:
            break;
          }
         
          return item;
        })
        
        const addLiveBasicInfo = {
          courseName,
          coverUrl: coverUrl || defaultCover,
          coverId,
          categoryId,
          categoryName
        };

        const liveDate = startTime;
        const timeHorizonStart = startTime;
        const timeHorizonEnd = endTime;
        const assistant = _.pluck(admins, "adminId");
        const assistantStoreUserId =  _.pluck(admins, "adminStoreUserId"); //编辑时的选中的助教的查询用storeUserId查询
        const assistantNames =  _.pluck(admins, "adminName");
        const addLiveClassInfo = {
          assistant,
          liveDate,
          nickname,
          teacherId,
          teacherName,
          timeHorizonStart,
          timeHorizonEnd,
          startTime,
          endTime,
          assistantNames,
          assistantStoreUserId
        }

        // liveCourseMediaRequests = liveCourseMediaRequests.length
        //   ? [...liveCourseMediaRequests]
        //   : [{ contentType:"INTRO",mediaType: 'TEXT', mediaContent: '', key: window.random_string(16) }, ...liveCourseMediaRequests];
        
        const addLiveIntroInfo = {
          liveCourseWarmMedia,
          needRecord,
          whetherVisitorsJoin,
          liveCourseMediaRequests,
        }

        // 晚于开课前30分钟
        if(new Date().getTime() > startTime - 1800000) {
          isEdit = false
        }
        this.setState({
          isEdit,
          loading: false,
          courseState,
          addLiveIntroInfo,
          addLiveClassInfo,
          addLiveBasicInfo,
        });
      })
  }

  // 修改基本信息
// 修改基本信息
handleChangeBasicInfo = (field, value) => {
  const { coverUrl } = this.state.addLiveBasicInfo;
  this.setState({
    addLiveBasicInfo: {
      ...this.state.addLiveBasicInfo,
      [field]: value,
    }
  })
}

  // 修改上课信息
  handleChangeClassInfo = (field, value ,type, optionValue) => {
    const _value = value ? value.valueOf() : null;
    const { teacherName } = this.state.addLiveClassInfo;
    const { assistantNames } = this.state.addLiveClassInfo;
    const { assistantStoreUserId } = this.state.addLiveClassInfo
    this.setState({
      addLiveClassInfo: {
        ...this.state.addLiveClassInfo,
        [field]: _value, 
        teacherName:type==='teacherType'?optionValue:teacherName,
        assistantNames:type==='assistantType'?_.pluck(optionValue, "children"):assistantNames,
        assistantStoreUserId:type==='assistantType'?_.pluck(optionValue, "key"):assistantStoreUserId,
      }
    });

    // 批量开始时间改变，结束时间自动同步一致
    if (field === 'startTime') {
      this.setState({
        addLiveClassInfo: {
          ...this.state.addLiveClassInfo,
          [field]: _value,
          endTime: _value,
        }
      });
    }
  }

  // 修改简介
  handleChangeIntroInfo = (field, value) => {
    this.setState({
      addLiveIntroInfo: {
        ...this.state.addLiveIntroInfo,
        [field]: value
      }
    })
  }

   // 完成创建/编辑
  handleSubmit = () => {
    const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, id, isEdit, type } = this.state;
    const {liveDate, timeHorizonStart} = addLiveClassInfo;
    const _liveDate = moment(liveDate).format("YYYY-MM-DD");
    const _timeHorizonStart = moment(timeHorizonStart).format('HH:mm');
    const startTime = moment(_liveDate + ' ' + _timeHorizonStart).format('x');
    if(type === 'edit' && isEdit && new Date().getTime() > startTime - 1800000) {
      Modal.info({
        title: "提示",
        icon: (
          <span className="icon iconfont default-confirm-icon">
            &#xe6f4;
          </span>
        ),
        content: "晚于开课前30分钟，部分信息不可修改",
        okText: '我知道了',
        onOk: () => {
          this.getCourseDetail();
        }
      });
      return
    }
    this.handleValidate(addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit).then((res)  => {
      if (!res) return;
      const { type } = this.state;
      const { courseName,coverUrl,coverId,categoryId} = addLiveBasicInfo;
      const {
        liveDate,
        teacherId,
        assistant,
        timeHorizonEnd,
        timeHorizonStart,
        calendarTime,
      } = addLiveClassInfo;

      let { startTime, endTime } = addLiveClassInfo;
      const { liveCourseMediaRequests, needRecord,whetherVisitorsJoin,liveCourseWarmMedia} = addLiveIntroInfo;

      if(type === 'add') {
        startTime = startTime;
        endTime = endTime;
      } else {
        const _liveDate = moment(liveDate).format("YYYY-MM-DD");
        const _timeHorizonStart = moment(timeHorizonStart).format('HH:mm');
        const _timeHorizonEnd = moment(timeHorizonEnd).format('HH:mm');
        startTime = moment(_liveDate + ' ' + _timeHorizonStart).format('x');
        endTime = moment(_liveDate + ' ' + _timeHorizonEnd).format('x');
      }
     
      let coverObj ={
        contentType:'COVER',
        mediaContent:coverId,
        mediaType:'PICTURE',
        mediaUrl: coverUrl,
      }
      let scheduleMediaRequests = [...liveCourseMediaRequests];
      if(coverId){
        scheduleMediaRequests = [coverObj,...scheduleMediaRequests]
      }
      if(liveCourseWarmMedia && liveCourseWarmMedia.mediaUrl){
        scheduleMediaRequests = [liveCourseWarmMedia,...scheduleMediaRequests]
      }
      const commonParams = {
        adminIds:assistant,
        calendarTime,
        categoryId,
        endTime,
        needRecord,
        startTime,
        courseName: courseName.trim(),
        storeId:User.getStoreId(),
        teacherId:teacherId,
        whetherVisitorsJoin,
        scheduleMediaRequests
      }

      if (type === 'add') {
        const params = {
          ...commonParams,
          operatorId:User.getUserId(),
        }

        CourseService.createLiveCloudCourse(params).then((res) => {
          if (res.success){
            message.success("新建成功");
            window.RCHistory.goBack();
          }  
        });

      } else {
        const params = {
          ...commonParams,
          updateUserId:User.getUserId(),
          liveCourseId: id,
        }
        // if(params.liveCourseWarmMedia && !params.liveCourseWarmMedia.mediaUrl) {
        //   delete params.liveCourseWarmMedia
        // }
        CourseService.updateLiveCloudCourse(params).then((res) => {
          if (res.success){
            message.success("更新成功");
            window.RCHistory.goBack();
          }
        });
      }
    })
  }
  handleValidate = (addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit) => {
    return new Promise((resolve) => {
      const { type } = this.state;
      const { courseName,categoryId} = addLiveBasicInfo;
      const {
        liveDate, timeHorizonStart, timeHorizonEnd, teacherId, calendarTime
      } = addLiveClassInfo;
      const { liveCourseMediaRequests } = addLiveIntroInfo;
      const currentTime = +new Date();

      if(!courseName) {
        message.warning('请输入课程名称');
        resolve(false);
        return;
      }

      if(!categoryId){
        message.warning('请选择课程分类');
        resolve(false);
        return;
      }

      if(type === 'add') {
        const { startTime, endTime } = addLiveClassInfo;
        if(calendarTime.length === 0) {
          message.warning('请选择上课日期');
          resolve(false);
          return; 
        } else if(startTime === endTime || startTime > endTime) {
          message.warning('结束时间必须晚于开始时间');
          resolve(false);
          return; 
        }
        // 若有今日排课 校验当前时间
        const currentDay = moment(currentTime).format('YYYY-MM-DD');
        const itemToday = _.find(calendarTime, (item) => {
          const itemDay = moment(item).format('YYYY-MM-DD');
          return itemDay === currentDay;
        })
        if(itemToday) {
          const itemDay = moment(itemToday).format('YYYY-MM-DD');
          const itemHour = moment(startTime).format('HH:mm');
          if(itemDay === currentDay) {
            if(moment(itemDay + ' ' + itemHour).format('x') < currentTime) {
              message.warning('开始时间不能早于现在');
              resolve(false);
              return;
            }
          }
        }
      } else {
        const _liveDate = moment(liveDate).format("YYYY-MM-DD");
        const _timeHorizonStart = moment(timeHorizonStart).format('HH:mm');
        const _timeHorizonEnd = moment(timeHorizonEnd).format('HH:mm');
  
        const startTime = moment(_liveDate + ' ' + _timeHorizonStart).format('x');
        const endTime = moment(_liveDate + ' ' + _timeHorizonEnd).format('x');
        if(!startTime || !endTime) {
          message.warning('日期不能为空');
          resolve(false);
          return;
        } else if (!timeHorizonStart) {
          message.warning('开始时间不能为空');
          resolve(false);
          return; 
        } else if (!timeHorizonEnd) {
          message.warning('结束时间不能为空');
          resolve(false);
          return; 
        } else if (isEdit && startTime < currentTime) {
          message.warning('开始时间不能早于当前时间');
          resolve(false);
          return; 
        } else if (isEdit && endTime < currentTime) {
          message.warning('结束时间不能早于当前时间');
          resolve(false);
          return; 
        } else if (isEdit && endTime <= startTime) {
          message.warning("结束时间不能早于开始时间");
          resolve(false);
          return; 
        }
      }
      if(!teacherId){
          message.warning('请选择讲师');
          resolve(false);
          return; 
      }
      resolve(true)
    });
  }

  // 显示预览课程弹窗
  handleShowPreviewModal = () => {
    const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo,type,courseState} = this.state;
    const previewLiveCourseModal = (
      <PreviewCourseModal
        courseBasicInfo={addLiveBasicInfo}
        courseClassInfo={addLiveClassInfo}
        courseIntroInfo={addLiveIntroInfo}
        type={type}
        courseState={courseState}
        close={() => {
          this.setState({
            previewLiveCourseModal: null
          })
        }}
      />
    );

    this.setState({ previewLiveCourseModal });
  }

  // 取消编辑并返回上一级路由
  handleGoBack = () => {
    // 比较state的addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo和默认数据是否相等
    const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo } = this.state;
    if (!_.isEqual(addLiveBasicInfo, defaultBasicInfo) ||
      !_.isEqual(addLiveClassInfo, defaultClassInfo) ||
      !_.isEqual(addLiveIntroInfo, defaultIntroInfo)
    ) {
      Modal.confirm({
        title: '确定要返回吗？',
        content: '返回后，本次编辑的内容将不被保存',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        onOk: () =>  {
          window.RCHistory.goBack();
        }
      })
    } else {
      window.RCHistory.goBack();
    }
  }

  render() {

    const {
      id, type,
      addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo,
      isEdit
    } = this.state;

    return (
      <div className="page add-live-page">
        <Breadcrumbs
          navList={type == "add" ? "新建直播课" : "编辑直播课"}
          goBack={this.handleGoBack}
        />
        <div className="box">
          <div className="show-tips">
            <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企培保有依据国家规定及平台规则进行处理的权利" />
          </div>
          <div className="add-live-page__form">
            <div className="basic-info__wrap">
              <div className="title">基本信息</div>
              <AddLiveBasic
                isEdit={isEdit}
                pageType={type}
                data={addLiveBasicInfo}
                onChange={this.handleChangeBasicInfo}
              />
            </div>

            <div className="class-info__wrap">
              <div className="title">上课信息</div>
              <AddLiveClass
                isEdit={isEdit}
                pageType={type}
                data={{...addLiveClassInfo, id} }
                onChange={this.handleChangeClassInfo}
              /> 
            </div>

            <div className="intro-info__wrap">
              <div className="title">更多信息</div>
              <AddLiveIntro
                isEdit={isEdit}
                data={addLiveIntroInfo}
                onChange={this.handleChangeIntroInfo}
              />
            </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>

        { this.state.previewLiveCourseModal }
        { this.state.lackConsumeStudentModal }
      </div>
    )
  }
}

export default withRouter(AddLive);