/*
 * @Author: 吴文洁
 * @Date: 2020-07-17 15:49:11
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-04-06 16:43:23
 * @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 Bus from '../../core/bus';

import AddLiveBasic from './components/AddLiveBasic';
import AddLiveClass from './components/AddLiveClass';
import AddLiveIntro from './components/AddLiveIntro';
import { randomString } from '@/domains/basic-domain/utils';
import Upload from '@/core/upload';
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 $ from 'jquery';
import './AddLive.less';

const defaultCover = 'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.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: {},
        introduce: '',
        liveCourseMediaRequests: [],
      },
    };
  }

  componentDidMount() {
    const { type } = this.state;
    if (type === 'edit') {
      this.getCourseDetail();
    }
    Bus.bind('editorLimit', (editorTextLength) => {
      this.setState({
        editorTextLength,
      });
    });
  }

  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;
      let hasIntro = false;
      courseMediaVOS.map((item) => {
        switch (item.contentType) {
          case 'COVER':
            coverId = item.mediaContent;
            coverUrl = item.mediaUrl;
            break;
          case 'WARMUP':
            liveCourseWarmMedia = item;
            break;
          case 'INTRO':
            hasIntro = true;
            this.getTextDetail('introduce', item.mediaUrl);
            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,
      };

      const addLiveIntroInfo = {
        liveCourseWarmMedia,
        needRecord,
        whetherVisitorsJoin,
        liveCourseMediaRequests,
      };

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

  getTextDetail = (key, url) => {
    $.ajax({
      data: {},
      type: 'GET',
      url,
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      success: (res) => {
        this.setState({ addLiveIntroInfo: { ...this.state.addLiveIntroInfo, [key]: res }, [`load${key}`]: true });
      },
      error: () => {
        message.warning('获取简介失败');
      },
    });
  };

  // 修改基本信息
  // 修改基本信息
  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,
      },
    });
  };

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

  // 完成创建/编辑
  handleSubmit = () => {
    //过期判断
    if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
      Modal.warning({
        title: '服务已到期',
        content: `当前企业购买的${window.brandName}服务已到期，如需继续使用学院功能，请尽快续费购买`,
        okText: '我知道了',
      });
      return;
    }
    const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, id, isEdit, type, editorTextLength } = 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, editorTextLength).then((res) => {
      if (!res) return;
      Upload.uploadTextToOSS(
        addLiveIntroInfo.introduce,
        `${randomString()}.txt`,
        (introduceId) => {
          this.submitRemote({ introduceId, addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, id });
        },
        () => message.warning('上传课程简介失败')
      );
    });
  };

  submitRemote = ({ introduceId, addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, id }) => {
    const { type } = this.state;
    const { courseName, coverUrl, coverId, categoryId } = addLiveBasicInfo;
    const { liveDate, teacherId, assistant, timeHorizonEnd, timeHorizonStart, calendarTime } = addLiveClassInfo;

    let { startTime, endTime } = addLiveClassInfo;
    const { 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 = [];
    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(),
        introduceId,
      };

      CourseService.createLiveCloudCourse(params).then((res) => {
        if (res.success) {
          message.success('新建成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      });
    } else {
      const params = {
        ...commonParams,
        updateUserId: User.getUserId(),
        liveCourseId: id,
        introduceId,
      };
      CourseService.updateLiveCloudCourse(params).then((res) => {
        if (res.success) {
          message.success('更新成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      });
    }
  };

  handleValidate = (addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit, editorTextLength) => {
    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;
      }

      if (editorTextLength > 1000) {
        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.push({
            pathname: `/live-course`,
          });
        },
      });
    } else {
      window.RCHistory.push({
        pathname: `/live-course`,
      });
    }
  };

  render() {
    const { id, type, addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit, loadintroduce } = 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={`请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，${window.brandName}保有依据国家规定及平台规则进行处理的权利`} />
          </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, loadintroduce, id }} onChange={this.handleChangeIntroInfo} />
            </div>
          </div>
        </div>

        <div className='footer shrink-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);
